package com.yjhh.chdataservice.service;

import com.yjhh.chdataservice.beans.*;
import com.yjhh.chdataservice.component.CommonDataComponent;
import com.yjhh.chdataservice.component.ESClientManager;
import com.yjhh.chdataservice.except.YJHHException;
import com.yjhh.chdataservice.util.CommonResultData;
import com.yjhh.chdataservice.util.DataConsts;
import com.yjhh.chdataservice.util.DataTools;
import com.yjhh.chdataservice.util.PageResultData;
import com.yjhh.chdataservice.util.XaUtil;
import lombok.extern.log4j.Log4j;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.lang.StringUtils;
import org.apache.http.client.utils.DateUtils;
import org.elasticsearch.action.search.SearchRequestBuilder;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.RangeQueryBuilder;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.aggregations.Aggregation;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.Aggregations;
import org.elasticsearch.search.aggregations.bucket.filter.FilterAggregationBuilder;
import org.elasticsearch.search.aggregations.bucket.filter.InternalFilter;
import org.elasticsearch.search.aggregations.bucket.filters.FiltersAggregationBuilder;
import org.elasticsearch.search.aggregations.bucket.filters.FiltersAggregator;
import org.elasticsearch.search.aggregations.bucket.filters.InternalFilters;
import org.elasticsearch.search.aggregations.bucket.range.InternalRange;
import org.elasticsearch.search.aggregations.bucket.range.RangeAggregationBuilder;
import org.elasticsearch.search.aggregations.bucket.terms.LongTerms;
import org.elasticsearch.search.aggregations.bucket.terms.StringTerms;
import org.elasticsearch.search.aggregations.bucket.terms.TermsAggregationBuilder;
import org.elasticsearch.search.aggregations.metrics.cardinality.CardinalityAggregationBuilder;
import org.elasticsearch.search.aggregations.metrics.cardinality.InternalCardinality;
import org.elasticsearch.search.aggregations.metrics.sum.InternalSum;
import org.elasticsearch.search.aggregations.metrics.sum.Sum;
import org.elasticsearch.search.aggregations.metrics.sum.SumAggregationBuilder;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.sort.FieldSortBuilder;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.StringTokenizer;

import static org.elasticsearch.index.query.QueryBuilders.boolQuery;
import static org.elasticsearch.index.query.QueryBuilders.existsQuery;
import static org.elasticsearch.index.query.QueryBuilders.matchQuery;
import static org.elasticsearch.index.query.QueryBuilders.prefixQuery;
import static org.elasticsearch.index.query.QueryBuilders.rangeQuery;
import static org.elasticsearch.index.query.QueryBuilders.termQuery;
import static org.elasticsearch.index.query.QueryBuilders.termsQuery;
import static org.elasticsearch.index.query.QueryBuilders.wildcardQuery;

/**
 * Created by hlantian on 2017/9/26.
 * 辅助决策安置点管理serviceImpl
 */
@Service
@Log4j2
public class FZJCPlacementPointServiceImpl implements FZJCPlacementPointService {
    
    @Autowired
    private ESClientManager esClientManager;
    
    @Autowired
    private CommonDataComponent commonDataComponent;
    
    @Value("${task.startyear}")
    private Integer taskStartYear;
    
    @Value("${task.endyear}")
    private Integer taskEndYear;
    
    @Value("${point.scale.range}")
    private String pointScaleRange;
    
    @Value("${pointmodule.scale.range}")
    private String pointModuleScaleRange;
    
    @Override
    public CommonResultData<List<PointStaticsInfoVo>> getPointStaticsByAreaCode(String areaCode) throws YJHHException {
        DeptBean sysDeptInfo = commonDataComponent.getSysDeptInfo(areaCode);
        if (sysDeptInfo == null) {
            return new CommonResultData<>(HttpStatus.OK.value(), "no data", null);
        }
        
        List<DeptBean> subDeptList = commonDataComponent.getSubDeptByDeptId(sysDeptInfo.getDeptID());
        
        List<PointStaticsInfoVo> pointStaticsInfoVoList = new ArrayList<>();
        
        PointStaticsInfoVo totalPointStaticsInfoVo = new PointStaticsInfoVo();
        totalPointStaticsInfoVo.setAreaName("合计");
        for (DeptBean deptBean : subDeptList) {
            PointStaticsInfoVo pointStaticsInfoVo = new PointStaticsInfoVo();
            pointStaticsInfoVo.setParentAreaCode(sysDeptInfo.getAreaCode());
            pointStaticsInfoVo.setParentAreaLevel(sysDeptInfo.getAreaLevel());
            pointStaticsInfoVo.setParentAreaName(sysDeptInfo.getDeptName());
            
            pointStaticsInfoVo.setAreaCode(deptBean.getAreaCode());
            pointStaticsInfoVo.setAreaLevel(deptBean.getAreaLevel());
            pointStaticsInfoVo.setAreaName(deptBean.getDeptName());
            
            fillPointInfoByAreaCode(deptBean, pointStaticsInfoVo);
            
            totalPointStaticsInfoVo.setSettlementPointNum(totalPointStaticsInfoVo.getSettlementPointNum() + pointStaticsInfoVo
                    .getSettlementPointNum());
            totalPointStaticsInfoVo.setSettlementPointBuildingNum_Co(totalPointStaticsInfoVo.getSettlementPointBuildingNum_Co() +
                                                                             pointStaticsInfoVo.getSettlementPointBuildingNum_Co());
            totalPointStaticsInfoVo.setSettlementPointBuildingNum_Pr(totalPointStaticsInfoVo.getSettlementPointBuildingNum_Pr() + pointStaticsInfoVo
                    .getSettlementPointBuildingNum_Pr());
            
            //TODO 此处需要更具具体的业务逻辑再做进一步的修改
            long settlementPointStartedNum_co = (totalPointStaticsInfoVo.getSettlementPointStartedNum_Co() + pointStaticsInfoVo
                    .getSettlementPointStartedNum_Co());
            totalPointStaticsInfoVo.setSettlementPointStartedNum_Co(settlementPointStartedNum_co > 0 ? settlementPointStartedNum_co - 1 :
                                                                            settlementPointStartedNum_co);
            totalPointStaticsInfoVo.setSettlementPointStartedNum_Pr(totalPointStaticsInfoVo.getSettlementPointStartedNum_Pr() + pointStaticsInfoVo
                    .getSettlementPointStartedNum_Pr());
            
            pointStaticsInfoVoList.add(pointStaticsInfoVo);
        }
        
        /*Collections.sort(pointStaticsInfoVoList, (PointStaticsInfoVo o1, PointStaticsInfoVo o2) -> {
            return o2.getSettlementPointNum() <= o1.getSettlementPointNum() ? 1 : -1;
        });*/
        
        pointStaticsInfoVoList.add(totalPointStaticsInfoVo);
        
        return new CommonResultData<>(HttpStatus.OK.value(), "suc", pointStaticsInfoVoList);
    }
    
    @Override
    public CommonResultData<List<PointScaleStaticsInfoVo>> getPointScaleStaticsByAreaCode(String areaCode) throws YJHHException {
        DeptBean sysDeptInfo = commonDataComponent.getSysDeptInfo(areaCode);
        if (sysDeptInfo == null) {
            return new CommonResultData<>(HttpStatus.OK.value(), "no data", null);
        }
    
        List<DeptBean> subDeptList = commonDataComponent.getSubDeptByDeptId(sysDeptInfo.getDeptID());
        List<PointScaleStaticsInfoVo> pointScaleStaticsInfoVoList = new ArrayList<>();
    
        PointScaleStaticsInfoVo totalPointStaticsInfoVo = new PointScaleStaticsInfoVo();
        totalPointStaticsInfoVo.setAreaName("合计");
        for(DeptBean deptBean : subDeptList) {
            PointScaleStaticsInfoVo pointScaleStaticsInfoVo = new PointScaleStaticsInfoVo();
            pointScaleStaticsInfoVo.setParentAreaCode(sysDeptInfo.getAreaCode());
            pointScaleStaticsInfoVo.setParentAreaLevel(sysDeptInfo.getAreaLevel());
            pointScaleStaticsInfoVo.setParentAreaName(sysDeptInfo.getDeptName());
    
            pointScaleStaticsInfoVo.setAreaCode(deptBean.getAreaCode());
            pointScaleStaticsInfoVo.setAreaLevel(deptBean.getAreaLevel());
            pointScaleStaticsInfoVo.setAreaName(deptBean.getDeptName());
            //安置点个数
            BoolQueryBuilder areacodequery = boolQuery().must(termQuery("a_deletestate", "0"));
            areacodequery.must(prefixQuery("a_deptno.keyword", deptBean.getDeptno()));
            areacodequery.must(termQuery("a_ispoint", 1));
    
            SearchRequestBuilder searchRequestBuilder = esClientManager.getESClient().prepareSearch("pl_placementpoint_inf").setTypes
                    ("placementpoint_inf")
                    .setSize(0);
            searchRequestBuilder.setQuery(areacodequery);
    
            RangeAggregationBuilder rangeAggregationBuilder = AggregationBuilders.range("pointScale")
                    .field("b_point_placement_allrs");
    
            //根据配置文件解析人口规模分段
            if (StringUtils.isBlank(pointModuleScaleRange)) {
                return new CommonResultData<>(HttpStatus.OK.value(), "no data", null);
            }
    
            StringTokenizer tokenParser = new StringTokenizer(pointModuleScaleRange, ",");
            int indexFlag = 0;
            while (tokenParser.hasMoreTokens()) {
                indexFlag++;
                String range = tokenParser.nextToken();
                String[] split = range.split("-");
                rangeAggregationBuilder.addRange("scale"+indexFlag, Double.parseDouble(split[0]), Double.parseDouble(split[1]));
            }
    
            searchRequestBuilder.addAggregation(rangeAggregationBuilder);
    
            log.info("request=" + searchRequestBuilder.toString());
            SearchResponse searchResponse = searchRequestBuilder.execute().actionGet();
            log.info("response=" + searchResponse.toString());
    
            long totalPlacementPointCount = searchResponse.getHits().getTotalHits();
            pointScaleStaticsInfoVo.setSettlementPointNum(totalPlacementPointCount);
     
            long diffHits = totalPlacementPointCount;
    
            Aggregations aggregations = searchResponse.getAggregations();
            InternalRange aggregation = (InternalRange) aggregations.asList().get(0);
    
            List<InternalRange.Bucket> buckets = aggregation.getBuckets();
            for (InternalRange.Bucket bucket : buckets) {
                String keyAsString = bucket.getKeyAsString();
                long docCount = bucket.getDocCount();
                diffHits -= docCount;
                if(StringUtils.equalsIgnoreCase("scale1",keyAsString)){
                    pointScaleStaticsInfoVo.setScale1(docCount);
                }else if(StringUtils.equalsIgnoreCase("scale2",keyAsString)){
                    pointScaleStaticsInfoVo.setScale2(docCount);
                }else if(StringUtils.equalsIgnoreCase("scale3",keyAsString)){
                    pointScaleStaticsInfoVo.setScale3(docCount);
                }else if(StringUtils.equalsIgnoreCase("scale4",keyAsString)){
                    pointScaleStaticsInfoVo.setScale4(docCount);
                }
            }
    
            //由于业务系统中很多数据没有安置点规划表数据，所以将0归为0-600人范围内
            pointScaleStaticsInfoVo.setScale1(pointScaleStaticsInfoVo.getScale1() + diffHits);
            
            pointScaleStaticsInfoVoList.add(pointScaleStaticsInfoVo);
            
            //计算合计
            totalPointStaticsInfoVo.setSettlementPointNum(totalPointStaticsInfoVo.getSettlementPointNum() + pointScaleStaticsInfoVo.getSettlementPointNum());
            totalPointStaticsInfoVo.setScale1(totalPointStaticsInfoVo.getScale1() + pointScaleStaticsInfoVo.getScale1());
            totalPointStaticsInfoVo.setScale2(totalPointStaticsInfoVo.getScale2() + pointScaleStaticsInfoVo.getScale2());
            totalPointStaticsInfoVo.setScale3(totalPointStaticsInfoVo.getScale3() + pointScaleStaticsInfoVo.getScale3());
            totalPointStaticsInfoVo.setScale4(totalPointStaticsInfoVo.getScale4() + pointScaleStaticsInfoVo.getScale4());
        }
    
     /*   Collections.sort(pointScaleStaticsInfoVoList, (PointScaleStaticsInfoVo o1, PointScaleStaticsInfoVo o2) -> {
            return o2.getSettlementPointNum() <= o1.getSettlementPointNum() ? 1 : -1;
        });*/
    
        pointScaleStaticsInfoVoList.add(totalPointStaticsInfoVo);
        
        return new CommonResultData<>(HttpStatus.OK.value(), "no data", pointScaleStaticsInfoVoList);
    }
    
    @Override
    public CommonResultData<List<PlacementPointSimpleVo>> getPlacementPointListByAreaCode(String areaCode) throws YJHHException {
        DeptBean sysDeptInfo = commonDataComponent.getSysDeptInfo(areaCode);
        BoolQueryBuilder areacodequery = boolQuery().must(termQuery("a_deletestate", "0"));
        areacodequery.must(termQuery("a_ispoint", "1"));
        areacodequery.must(prefixQuery("a_deptno.keyword", sysDeptInfo.getDeptno()));
        
        SearchRequestBuilder searchRequestBuilder = esClientManager.getESClient().prepareSearch("pl_placementpoint_inf").setTypes
                ("placementpoint_inf");
        
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        searchSourceBuilder.fetchSource(new String[]{"a_areacode", "a_deptname", "a_pointid", "a_projname", "a_pointx", "a_pointy", "a_allareas",
                "b_point_placement_allhs"}, null);
        searchSourceBuilder.query(areacodequery);
        FieldSortBuilder sort = new FieldSortBuilder("a_deptno.keyword");
        searchSourceBuilder.sort(sort);
        searchSourceBuilder.size(10000);
        
        searchRequestBuilder.setSource(searchSourceBuilder);
        
        log.info("request=" + searchRequestBuilder.toString());
        SearchResponse searchResponse = searchRequestBuilder.execute().actionGet();
        log.info("response=" + searchResponse.toString());
        
        SearchHit[] searchHits = searchResponse.getHits().getHits();
        
        List<PlacementPointSimpleVo> pointSimpleVoList = new ArrayList<>();
        for (SearchHit searchHit : searchHits) {
            Map<String, Object> searchHitSource = searchHit.getSource();
            
            pointSimpleVoList.add(new PlacementPointSimpleVo(
                    DataTools.convertToStr(searchHitSource.get("a_allareas")),
                    DataTools.convertToStr(searchHitSource.get("a_areacode")),
                    DataTools.convertToStr(searchHitSource.get("a_deptname")),
                    DataTools.convertToStr(searchHitSource.get("a_pointid")),
                    DataTools.convertToStr(searchHitSource.get("b_point_placement_allhs")),
                    StringUtils.isBlank(DataTools.convertToStr(searchHitSource.get("a_pointx"))) ? 0.0 : Double
                            .parseDouble
                                    (DataTools.convertToStr(searchHitSource.get("a_pointx"))),
                    StringUtils.isBlank(DataTools.convertToStr(searchHitSource.get("a_pointy"))) ? 0.0 : Double
                            .parseDouble
                                    (DataTools.convertToStr(searchHitSource.get("a_pointy"))),
                    DataTools.convertToStr(searchHitSource.get("a_projname"))));
            
        }
        return new CommonResultData<>(HttpStatus.OK.value(), "suc", pointSimpleVoList);
    }
    
    @Override
    public CommonResultData<PlacementPointDetailVo> getPlacementPointDetailByPointId(String pointId) throws YJHHException {
        QueryBuilder idsQueryBuilder = QueryBuilders.idsQuery().addIds(pointId);
        SearchRequestBuilder searchRequestBuilder = esClientManager.getESClient().prepareSearch("pl_placementpoint_inf").setTypes
                ("placementpoint_inf").setQuery(idsQueryBuilder);
        
        log.info("reqeust: " + searchRequestBuilder.toString());
        SearchResponse searchResponse = searchRequestBuilder.execute().actionGet();
        log.info("response:" + searchResponse.toString());
        
        SearchHit[] hits = searchResponse.getHits().getHits();
        if (hits == null || hits.length <= 0) {
            new CommonResultData<>(HttpStatus.OK.value(), "suc", null);
        }
        
        Map<String, Object> searchHitSource = hits[0].getSource();
        
        //安置点基本信息--------------------------------------------------------------------
        PlacementPointBaseInfoVo placementPointBaseInfoVo = new PlacementPointBaseInfoVo(
                DataTools.convertToStr(searchHitSource.get("a_allareas"), "亩"),
                DataTools.convertToStr(searchHitSource.get("a_constructioncycle")),
                commonDataComponent.getSysDicValueById(DataTools.convertToStr(searchHitSource.get("a_demostate"))),
                XaUtil.dateConvertYYYYMMDD(searchHitSource.get("a_endprojecttime")),
                DataTools.convertToStr(searchHitSource.get("a_firstyear")),
                commonDataComponent.getSysDicValueById(DataTools.convertToStr(searchHitSource.get("a_housetype"))),
                StringUtils.equalsIgnoreCase("1", DataTools.convertToStr(searchHitSource.get("a_isincity"))) ? "是" : "否",
                DataTools.convertToStr(searchHitSource.get("a_pointaddress")),
                pointId,
                commonDataComponent.getSysDicValueById(DataTools.convertToStr(searchHitSource.get("a_pointtype"))),
                StringUtils.isBlank(DataTools.convertToStr(searchHitSource.get("a_pointx"))) ? 0.0 : Double
                        .parseDouble
                                (DataTools.convertToStr(searchHitSource.get("a_pointx"))),
                StringUtils.isBlank(DataTools.convertToStr(searchHitSource.get("a_pointy"))) ? 0.0 : Double
                        .parseDouble
                                (DataTools.convertToStr(searchHitSource.get("a_pointy"))),
                DataTools.convertToStr(searchHitSource.get("a_projname")),
                XaUtil.dateConvert(searchHitSource.get("a_recordtime")),
                commonDataComponent.getSysDicValueById(DataTools.convertToStr(searchHitSource.get("a_seladdress"))),
                XaUtil.dateConvertYYYYMMDD(searchHitSource.get("a_startprojecttime")),
                DataTools.convertToStr(searchHitSource.get("a_usercname")));
        
        //安置住房信息--------------------------------------------------------------------
        PlacementHouseInfoVo placementHouseInfoVo = new PlacementHouseInfoVo(
                DataTools.convertToStr(searchHitSource.get("b_point_contruction_alltz"), "万元"),
                DataTools.convertToStr(searchHitSource.get("b_point_contruction_bzmj"), "平方米"),
                DataTools.convertToStr(searchHitSource.get("b_point_contruction_qzjdlipkmj"), "平方米"),
                DataTools.convertToStr(searchHitSource.get("b_point_contruction_qzjdlipktz"), "万元"),
                DataTools.convertToStr(searchHitSource.get("b_point_contruction_stmj"), "平方米"),
                DataTools.convertToStr(searchHitSource.get("b_point_placement_allhs")),
                DataTools.convertToStr(searchHitSource.get("b_point_placement_bzhs"), "套"),
                DataTools.convertToStr(searchHitSource.get("b_point_placement_qzjdlipkhs"), "套"),
                DataTools.convertToStr(searchHitSource.get("b_point_placement_sths"), "套"),
                pointId);
        
        //基础配套-----------------------------------------------------------------------
        PlacementBaseSupportServiceVo placementBaseSupportServiceVo = new PlacementBaseSupportServiceVo(
                DataTools.convertToStr(searchHitSource.get("b_point_contruction_basealltz"), "万元"),
                DataTools.convertToStr(searchHitSource.get("b_point_contruction_dlyhcd"), "米"),
                DataTools.convertToStr(searchHitSource.get("b_point_contruction_dlyhzj"), "万元"),
                DataTools.convertToStr(searchHitSource.get("b_point_contruction_hwsscd"), "米"),
                DataTools.convertToStr(searchHitSource.get("b_point_contruction_hwsszj"), "万元"),
                DataTools.convertToStr(searchHitSource.get("b_point_contruction_jcqtzj"), "万元"),
                DataTools.convertToStr(searchHitSource.get("b_point_contruction_sdxlcd"), "米"),
                DataTools.convertToStr(searchHitSource.get("b_point_contruction_sdxlzj"), "万元"),
                DataTools.convertToStr(searchHitSource.get("b_point_contruction_ssgdcd"), "米"),
                DataTools.convertToStr(searchHitSource.get("b_point_contruction_ssgdzj"), "万元"),
                pointId);
        
        //公共服务信息-----------------------------------------------------------------
        PlacementPublicServiceVo placementPublicServiceVo = new PlacementPublicServiceVo(
                DataTools.convertToStr(searchHitSource.get("b_point_contruction_ggqtcd"), "亩"),
                DataTools.convertToStr(searchHitSource.get("b_point_contruction_ggqtgs"), "个"),
                DataTools.convertToStr(searchHitSource.get("b_point_contruction_ggqtzj"), "万元"),
                DataTools.convertToStr(searchHitSource.get("b_point_contruction_hdscd"), "亩"),
                DataTools.convertToStr(searchHitSource.get("b_point_contruction_hdsgs"), "个"),
                DataTools.convertToStr(searchHitSource.get("b_point_contruction_hdszj"), "万元"),
                DataTools.convertToStr(searchHitSource.get("b_point_contruction_publicalltz"), "万元"),
                DataTools.convertToStr(searchHitSource.get("b_point_contruction_wsyscd"), "亩"),
                DataTools.convertToStr(searchHitSource.get("b_point_contruction_wsysgs"), "个"),
                DataTools.convertToStr(searchHitSource.get("b_point_contruction_wsyszj"), "万元"),
                DataTools.convertToStr(searchHitSource.get("b_point_contruction_xxcd"), "亩"),
                DataTools.convertToStr(searchHitSource.get("b_point_contruction_xxgs"), "个"),
                DataTools.convertToStr(searchHitSource.get("b_point_contruction_xxzj"), "万元"),
                DataTools.convertToStr(searchHitSource.get("b_point_contruction_yrycd"), "亩"),
                DataTools.convertToStr(searchHitSource.get("b_point_contruction_yrygs"), "个"),
                DataTools.convertToStr(searchHitSource.get("b_point_contruction_yryzj"), "万元"),
                pointId);
        
        
        //脱贫产业-----------------------------------------------------------------------
        PlacementTPCYVo placementTPCYVo = new PlacementTPCYVo(
                DataTools.convertToStr(searchHitSource.get("b_point_contruction_alljob")),
                DataTools.convertToStr(searchHitSource.get("b_point_contruction_ccxy")),
                DataTools.convertToStr(searchHitSource.get("b_point_contruction_gyxgw")),
                DataTools.convertToStr(searchHitSource.get("b_point_contruction_lwsc")),
                DataTools.convertToStr(searchHitSource.get("b_point_contruction_mjxgy")),
                DataTools.convertToStr(searchHitSource.get("b_point_contruction_shbzdd")),
                DataTools.convertToStr(searchHitSource.get("b_point_contruction_tpgwqt")),
                DataTools.convertToStr(searchHitSource.get("b_point_contruction_tsnly")),
                DataTools.convertToStr(searchHitSource.get("b_point_contruction_xdfwy")),
                DataTools.convertToStr(searchHitSource.get("b_point_contruction_zzcy")),
                pointId);
        
        return new CommonResultData<>(HttpStatus.OK.value(), "suc", new PlacementPointDetailVo(placementPointBaseInfoVo, placementPublicServiceVo
                , placementHouseInfoVo, placementTPCYVo, placementBaseSupportServiceVo));
    }
    
    @Override
    public CommonResultData<PlacementPointServiceStatisticsVo> getPlacementPointServicesStatisticsByAreaCode(String areaCode) throws YJHHException {
        DeptBean sysDeptInfo = commonDataComponent.getSysDeptInfo(areaCode);
        if (sysDeptInfo == null) {
            return new CommonResultData<>(HttpStatus.OK.value(), "no data", null);
        }
        List<DeptBean> subDept = commonDataComponent.getSubDeptByDeptId(sysDeptInfo.getDeptID());
        if (subDept == null || subDept.size() <= 0) {
            return new CommonResultData<>(HttpStatus.OK.value(), "no data", null);
        }
        //提取子部门ID为数组
        List<String> deptIds = new ArrayList<>();
        List<String> deptNameList = new ArrayList<>();
        List<Integer> zxxList = new ArrayList<>();
        List<Integer> yeyList = new ArrayList<>();
        List<Integer> wsysList = new ArrayList<>();
        List<Integer> hdsList = new ArrayList<>();
        List<Integer> qtList = new ArrayList<>();
        for (DeptBean deptBean : subDept) {
            deptIds.add(deptBean.getDeptID());
            deptNameList.add(deptBean.getDeptName());
            zxxList.add(0);
            yeyList.add(0);
            wsysList.add(0);
            hdsList.add(0);
            qtList.add(0);
        }
        
        
        BoolQueryBuilder areacodequery = boolQuery().must(termQuery("deletestate", "0"));
        areacodequery.must(termQuery("stype", "1"));
        areacodequery.must(termsQuery("deptid.keyword", deptIds));
        areacodequery.filter(existsQuery("deptname.keyword"));
        
        SearchRequestBuilder searchRequestBuilder = esClientManager.getESClient().prepareSearch("pl_pointprograming_inf").setTypes
                ("pointprograming_inf");
        
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        searchSourceBuilder.fetchSource(new String[]{"deptid", "deptname", "point_contruction_xxgs", "point_contruction_yrygs",
                "point_contruction_wsysgs", "point_contruction_hdsgs", "point_contruction_ggqtgs"}, null);
        searchSourceBuilder.query(areacodequery);
        FieldSortBuilder sort = new FieldSortBuilder("deptno.keyword");
        searchSourceBuilder.sort(sort);
        searchSourceBuilder.size(10000);
        
        searchRequestBuilder.setSource(searchSourceBuilder);
        
        log.info("request=" + searchRequestBuilder.toString());
        SearchResponse searchResponse = searchRequestBuilder.execute().actionGet();
        
        SearchHit[] searchHits = searchResponse.getHits().getHits();
        for (SearchHit searchHit : searchHits) {
            Map<String, Object> searchHitSource = searchHit.getSource();
            String deptname = DataTools.convertToStr(searchHitSource.get("deptname"));
            int deptNameIndex = deptNameList.indexOf(deptname);
            zxxList.set(deptNameIndex, DataTools.stringToInt(DataTools.convertToStr(searchHitSource.get("point_contruction_xxgs"))));         //中小学
            yeyList.set(deptNameIndex, DataTools.stringToInt(DataTools.convertToStr(searchHitSource.get("point_contruction_yrygs"))));        //幼儿园
            wsysList.set(deptNameIndex, DataTools.stringToInt(DataTools.convertToStr(searchHitSource.get("point_contruction_wsysgs"))));        //卫生院所
            hdsList.set(deptNameIndex, DataTools.stringToInt(DataTools.convertToStr(searchHitSource.get("point_contruction_hdsgs"))));        //活动室
            qtList.set(deptNameIndex, DataTools.stringToInt(DataTools.convertToStr(searchHitSource.get("point_contruction_ggqtgs"))));         //其他
        }
        
        List<PlacementPointServiceStatisticsSubVo> chartdata = new ArrayList<>();
        
        chartdata.add(new PlacementPointServiceStatisticsSubVo(zxxList, "中小学"));
        chartdata.add(new PlacementPointServiceStatisticsSubVo(yeyList, "幼儿园"));
        chartdata.add(new PlacementPointServiceStatisticsSubVo(wsysList, "卫生院所"));
        chartdata.add(new PlacementPointServiceStatisticsSubVo(hdsList, "活动室"));
        chartdata.add(new PlacementPointServiceStatisticsSubVo(qtList, "其他"));
        
        return new CommonResultData<>(HttpStatus.OK.value(), "suc", new PlacementPointServiceStatisticsVo(deptNameList, chartdata));
    }
    
    @Override
    public CommonResultData<List<PlacementPointPlanVo>> getPlacementPointYearPlanByAreaCode(String areaCode) throws YJHHException {
        DeptBean sysDeptInfo = commonDataComponent.getSysDeptInfo(areaCode);
        if (sysDeptInfo == null) {
            return new CommonResultData<>(HttpStatus.OK.value(), "no data", null);
        }
        List<DeptBean> subDept = commonDataComponent.getSubDeptByDeptId(sysDeptInfo.getDeptID());
        if (subDept == null || subDept.size() <= 0) {
            return new CommonResultData<>(HttpStatus.OK.value(), "no data", null);
        }
        
        List<PlacementPointPlanVo> resultList = new ArrayList<>();
        for (DeptBean deptBean : subDept) {
            String deptno = deptBean.getDeptno();
            resultList.add(new PlacementPointPlanVo(getCOPlacementPointYearPlanByAreaCode(deptno), getPRPlacementPointYearPlanByAreaCode(deptno),
                                                    deptBean.getDeptName()));
        }
        
        return new CommonResultData<>(HttpStatus.OK.value(), "suc", resultList);
    }
    
    /**
     * 获取国家安置点年规划个数
     *
     * @param deptno
     */
    private List<PlacementPointPlanYearVo> getCOPlacementPointYearPlanByAreaCode(String deptno) throws YJHHException {
        BoolQueryBuilder areacodequery = boolQuery().must(termQuery("stype", "0"));
        areacodequery.must(prefixQuery("plco_deptno.keyword", deptno));
        
        SearchRequestBuilder searchRequestBuilder = esClientManager.getESClient().prepareSearch("pl_planco_placementpoint_inf").setTypes
                ("planco_placementpoint_inf")
                .setSize(0);
        searchRequestBuilder.setQuery(areacodequery);
        
        TermsAggregationBuilder deptsAgg = AggregationBuilders.terms("yearTask").field("plco_taskyear").size(10000);
        searchRequestBuilder.addAggregation(deptsAgg);
        
        log.info("request=" + searchRequestBuilder.toString());
        SearchResponse searchResponse = searchRequestBuilder.execute().actionGet();
        log.info("response=" + searchResponse.toString());
        
        return parseAggData(searchResponse);
    }
    
    /**
     * 解析结果数据，并封装为统一格式
     *
     * @param searchResponse
     * @return
     */
    private List<PlacementPointPlanYearVo> parseAggData(SearchResponse searchResponse) {
        Aggregations aggregations = searchResponse.getAggregations();
        LongTerms aggregation = (LongTerms) aggregations.asList().get(0);
        List<LongTerms.Bucket> buckets = aggregation.getBuckets();
        
        Map<String, Long> yearCountMap = new HashMap<>();
        for (int i = taskStartYear; i <= taskEndYear; i++) {
            yearCountMap.put(i + "", 0L);
        }
        
        for (LongTerms.Bucket bucket : buckets) {
            yearCountMap.put(bucket.getKeyAsString(), bucket.getDocCount());
        }
        
        List<PlacementPointPlanYearVo> resultList = new ArrayList<>();
        for (Map.Entry<String, Long> entry : yearCountMap.entrySet()) {
            resultList.add(new PlacementPointPlanYearVo(entry.getValue(), entry.getKey()));
        }
        return resultList;
    }
    
    /**
     * 获取省安置点年规划个数
     *
     * @param deptno
     */
    private List<PlacementPointPlanYearVo> getPRPlacementPointYearPlanByAreaCode(String deptno) throws YJHHException {
        BoolQueryBuilder areacodequery = boolQuery().must(termQuery("stype", "0"));
        areacodequery.must(prefixQuery("plpr_deptno.keyword", deptno));
        
        SearchRequestBuilder searchRequestBuilder = esClientManager.getESClient().prepareSearch("pl_planpr_placementpoint_inf").setTypes
                ("planpr_placementpoint_inf")
                .setSize(0);
        searchRequestBuilder.setQuery(areacodequery);
        
        TermsAggregationBuilder deptsAgg = AggregationBuilders.terms("yearTask").field("plpr_taskyear").size(10000);
        searchRequestBuilder.addAggregation(deptsAgg);
        
        log.info("request=" + searchRequestBuilder.toString());
        SearchResponse searchResponse = searchRequestBuilder.execute().actionGet();
        log.info("response=" + searchResponse.toString());
        
        return parseAggData(searchResponse);
    }
    
    
    @Override
    public CommonResultData<List<TPJYPostTypeInfoVo>> getJYGWInfoByAreaCode(String areaCode) throws YJHHException {
        DeptBean sysDeptInfo = commonDataComponent.getSysDeptInfo(areaCode);
        BoolQueryBuilder areacodequery = boolQuery().must(termQuery("deletestate", "0"));
        areacodequery.must(termQuery("stype", "1"));
        areacodequery.must(termsQuery("deptid.keyword", sysDeptInfo.getDeptID()));
        areacodequery.filter(existsQuery("deptname.keyword"));
        
        SearchRequestBuilder searchRequestBuilder = esClientManager.getESClient().prepareSearch("pl_pointprograming_inf").setTypes
                ("pointprograming_inf");
        
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        searchSourceBuilder.fetchSource(new String[]{"deptid",  //部门ID
                "deptname",  //部门名称
                "point_contruction_tsnly",  //特色农林业
                "point_contruction_mjxgy",//劳动密集型工业
                "point_contruction_xdfwy",  //现代服务业
                "point_contruction_lwsc",   //劳务输出
                "point_contruction_shbzdd",   //社会保障兜底
                "point_contruction_gyxgw",   //公益性岗位
                "point_contruction_zzcy",   //自助创业
                "point_contruction_tpgwqt"   //就业脱贫规划岗位其他
        }, null);
        searchSourceBuilder.query(areacodequery);
        searchSourceBuilder.size(10000);
        
        searchRequestBuilder.setSource(searchSourceBuilder);
        
        log.info("request=" + searchRequestBuilder.toString());
        SearchResponse searchResponse = searchRequestBuilder.execute().actionGet();
        log.info("response=" + searchResponse.toString());
        
        SearchHit[] hits = searchResponse.getHits().getHits();
        List<TPJYPostTypeInfoVo> resultList = new ArrayList<>();
        for (SearchHit hit : hits) {
            Map<String, Object> source = hit.getSource();
            resultList.add(new TPJYPostTypeInfoVo(DataTools.stringToInt(DataTools.convertToStr(source.get("point_contruction_tsnly"))), "特色农业"));
            resultList.add(new TPJYPostTypeInfoVo(DataTools.stringToInt(DataTools.convertToStr(source.get("point_contruction_mjxgy"))), "劳动密集型"));
            resultList.add(new TPJYPostTypeInfoVo(DataTools.stringToInt(DataTools.convertToStr(source.get("point_contruction_xdfwy"))), "服务业"));
            resultList.add(new TPJYPostTypeInfoVo(DataTools.stringToInt(DataTools.convertToStr(source.get("point_contruction_lwsc"))), "劳务输出"));
            resultList.add(new TPJYPostTypeInfoVo(DataTools.stringToInt(DataTools.convertToStr(source.get("point_contruction_shbzdd"))), "兜底保障"));
            resultList.add(new TPJYPostTypeInfoVo(DataTools.stringToInt(DataTools.convertToStr(source.get("point_contruction_gyxgw"))), "公益性"));
            resultList.add(new TPJYPostTypeInfoVo(DataTools.stringToInt(DataTools.convertToStr(source.get("point_contruction_zzcy"))), "自主创业"));
            resultList.add(new TPJYPostTypeInfoVo(DataTools.stringToInt(DataTools.convertToStr(source.get("point_contruction_tpgwqt"))), "其他"));
        }
        if (resultList.size() <= 0) {
            resultList.add(new TPJYPostTypeInfoVo(0, "特色农业"));
            resultList.add(new TPJYPostTypeInfoVo(0, "劳动密集型"));
            resultList.add(new TPJYPostTypeInfoVo(0, "服务业"));
            resultList.add(new TPJYPostTypeInfoVo(0, "劳务输出"));
            resultList.add(new TPJYPostTypeInfoVo(0, "兜底保障"));
            resultList.add(new TPJYPostTypeInfoVo(0, "公益性"));
            resultList.add(new TPJYPostTypeInfoVo(0, "自主创业"));
            resultList.add(new TPJYPostTypeInfoVo(0, "其他"));
        }
        return new CommonResultData<>(HttpStatus.OK.value(), "suc", resultList);
    }
    
    @Override
    public CommonResultData<PlacementPointStartedAndMoveInVo> getPointStartedAndMoveInStatisticsByAreaCode(String areaCode) throws YJHHException {
        DeptBean sysDeptInfo = commonDataComponent.getSysDeptInfo(areaCode);
        return new CommonResultData<>(HttpStatus.OK.value(), "suc",
                                      new PlacementPointStartedAndMoveInVo(getRuZhuPercent(sysDeptInfo.getDeptno()),
                                                                           getPlacementPointStartedPercent(sysDeptInfo.getDeptno())));
    }
    
    @Override
    public CommonResultData<List<PlacementPointSimpleInfoVo>> getAllPlacementPointByAreaCode(String areaCode, String areaType) throws YJHHException {
        DeptBean sysDeptInfo = commonDataComponent.getSysDeptInfo(areaCode);
        BoolQueryBuilder areacodequery = boolQuery().must(termQuery("a_deletestate", "0"));
        areacodequery.must(prefixQuery("a_deptno.keyword", sysDeptInfo.getDeptno()));
        
        SearchRequestBuilder searchRequestBuilder = esClientManager.getESClient().prepareSearch("pl_placementpoint_inf").setTypes
                ("placementpoint_inf")
                .setSize(100000);
        
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        searchSourceBuilder.fetchSource(new String[]{"b_point_placement_allrs",
                "a_pointid",
                "a_pointx",
                "a_pointy",
                "a_projname",
                "a_deptid"
        }, null);
        searchSourceBuilder.query(areacodequery);
        searchSourceBuilder.size(10000);
        
        searchRequestBuilder.setSource(searchSourceBuilder);
        
        log.info("request=" + searchRequestBuilder.toString());
        SearchResponse searchResponse = searchRequestBuilder.execute().actionGet();
        log.info("response=" + searchResponse.toString());
        
        SearchHit[] hits = searchResponse.getHits().getHits();
        
        List<PlacementPointSimpleInfoVo> resultList = new ArrayList<>();
        for (SearchHit searchHit : hits) {
            Map<String, Object> source = searchHit.getSource();
            String deptId = DataTools.convertToStr(source.get
                    ("a_deptid"));
            //获取所属区域类型
            String deptAreaType = "";
            if (StringUtils.isNotBlank(deptId) && commonDataComponent.getDeptByDeptId(deptId) != null) {
                deptAreaType = commonDataComponent.getDeptByDeptId(deptId).getAreaType();
            }
            
            //需要根据条件进行过来,areaType为空表示查询全部，不为空则查询条件提供的areaType的数据
            if (StringUtils.isBlank(areaType) || StringUtils.equalsIgnoreCase(deptAreaType, areaType)) {
                resultList.add(new PlacementPointSimpleInfoVo(deptAreaType,
                                                              DataTools.stringToInt(DataTools.convertToStr(source.get("b_point_placement_allrs"))),
                                                              DataTools.convertToStr(source.get("a_pointid")),
                                                              StringUtils.isBlank(DataTools.convertToStr(source.get("a_pointx"))) ? 0.0 : Double
                                                                      .parseDouble
                                                                              (DataTools.convertToStr(source.get("a_pointx"))),
                                                              StringUtils.isBlank(DataTools.convertToStr(source.get("a_pointy"))) ? 0.0 : Double
                                                                      .parseDouble
                                                                              (DataTools.convertToStr(source.get("a_pointy"))),
                                                              DataTools.convertToStr(source.get("a_projname"))));
            }
        }
        
        return new CommonResultData<>(HttpStatus.OK.value(), "suc", resultList);
    }
    
    @Override
    public CommonResultData<PointVillageAndPeopleVo> getMoveInPointVillageAndPeopleCountByPointId(String pointId) throws YJHHException {
        //获取安置点信息
        QueryBuilder idsQueryBuilder = QueryBuilders.idsQuery().addIds(pointId);
        SearchRequestBuilder searchRequestBuilder = esClientManager.getESClient().prepareSearch("pl_placementpoint_inf").setTypes
                ("placementpoint_inf").setQuery
                (idsQueryBuilder);
        
        
        log.info("reqeust: " + searchRequestBuilder.toString());
        SearchResponse searchResponse = searchRequestBuilder.execute().actionGet();
        log.info("response:" + searchResponse.toString());
        
        SearchHit[] hits = searchResponse.getHits().getHits();
        
        if (hits.length <= 0) {
            return new CommonResultData<>(HttpStatus.OK.value(), "no data", null);
        }
        Map<String, Object> source = hits[0].getSource();
       log.info(source.get("a_projname") + "    " + source.get("a_pointx") + "       " + source.get("a_pointy"));
        
        //获取搬迁入安置点的村子以及
        BoolQueryBuilder areacodequery = boolQuery().must(termQuery("isdelete", "0"));
        areacodequery.must(termQuery("objmovesupinf.obj_movesup_azdid.keyword", pointId));
        searchRequestBuilder = esClientManager.getESClient().prepareSearch("obj_reloca_info").setTypes("reloca_info").setSize(0).setQuery
                (areacodequery);
        TermsAggregationBuilder deptsAgg = AggregationBuilders.terms("depts").field("deptid.keyword").missing(DataConsts.UNKNOWN)
                .size(10000);
        
        //按存分组后求每个家庭的人数之和
        deptsAgg.subAggregation(AggregationBuilders.sum("familyMemberCount").field("familyMemberCount"));
        
        searchRequestBuilder.addAggregation(deptsAgg);
        log.info("reqeust: " + searchRequestBuilder.toString());
        searchResponse = searchRequestBuilder.execute().actionGet();
        log.info("response:" + searchResponse.toString());
        
        List<Aggregation> aggregations = searchResponse.getAggregations().asList();
        
        if (aggregations == null || aggregations.size() <= 0) {
            return new CommonResultData<>(HttpStatus.OK.value(), "no data", null);
        }
        
        List<PointVillageAndPeopleVoSub> subList = new ArrayList<>();
        StringTerms stringTerms = (StringTerms) aggregations.get(0);
        for (StringTerms.Bucket bucket : stringTerms.getBuckets()) {
            String deptId = bucket.getKeyAsString();
            //搬迁户数
            DeptBean deptBean = commonDataComponent.getDeptByDeptId(deptId);
            InternalSum aggregation = (InternalSum) bucket.getAggregations().asList().get(0);
            
            subList.add(new PointVillageAndPeopleVoSub(deptId, deptBean.getDeptName(), (int) aggregation.getValue(), deptBean.getX(), deptBean.getY
                    ()));
        }
        
        PointVillageAndPeopleVo pointVillageAndPeopleVo = new PointVillageAndPeopleVo(pointId,
                                                                                      DataTools.convertToStr(source.get("a_projname")),
                                                                                      StringUtils.isBlank(DataTools.convertToStr(source.get
                                                                                              ("a_pointx"))) ? 0.0 : Double
                                                                                              .parseDouble
                                                                                                      (DataTools.convertToStr(source.get
                                                                                                              ("a_pointx"))),
                                                                                      StringUtils.isBlank(DataTools.convertToStr(source.get
                                                                                              ("a_pointy"))) ? 0.0 : Double
                                                                                              .parseDouble
                                                                                                      (DataTools.convertToStr(source.get
                                                                                                              ("a_pointy"))),
                                                                                      subList);
        
        return new CommonResultData<>(HttpStatus.OK.value(), "suc", pointVillageAndPeopleVo);
    }
    
    /**
     * 获取安置点开工率
     *
     * @param deptno
     */
    private double getPlacementPointStartedPercent(String deptno) throws YJHHException {
        BoolQueryBuilder areacodequery = boolQuery().must(termQuery("a_deletestate", "0"));
        areacodequery.must(termQuery("a_ispoint", "1"));
        areacodequery.must(prefixQuery("a_deptno.keyword", deptno));
        
        SearchRequestBuilder searchRequestBuilder = esClientManager.getESClient().prepareSearch("pl_placementpoint_inf").setTypes
                ("placementpoint_inf")
                .setSize(0);
        searchRequestBuilder.setQuery(areacodequery);
        
        FilterAggregationBuilder filterAggregationBuilder = AggregationBuilders.filter("yearTask", existsQuery("a_startprojecttime"));
        searchRequestBuilder.addAggregation(filterAggregationBuilder);
        
        log.info("request=" + searchRequestBuilder.toString());
        SearchResponse searchResponse = searchRequestBuilder.execute().actionGet();
        log.info("response=" + searchResponse.toString());
        
        Aggregations aggregations = searchResponse.getAggregations();
        InternalFilter internalFilter = (InternalFilter) aggregations.asList().get(0);
        
        long totalPoint = searchResponse.getHits().getTotalHits();
        long startedPoint = internalFilter.getDocCount();
        if (totalPoint == 0) {
            return 0.0;
        }
        BigDecimal bigDecimal = new BigDecimal(((double) startedPoint / (double) totalPoint) * 100);
        return bigDecimal.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
    }
    
    /**
     * 入住率
     *
     * @param deptno
     * @return
     * @throws YJHHException
     */
    public double getRuZhuPercent(String deptno) throws YJHHException {
        BoolQueryBuilder areacodequery = boolQuery().must(termQuery("isdelete", "0"));
        areacodequery.must(prefixQuery("deptno.keyword", deptno));
        SearchRequestBuilder searchRequestBuilder = esClientManager.getESClient().prepareSearch("obj_reloca_info").setTypes("reloca_info").setSize
                (0).setQuery
                (areacodequery);
        
        //入住状态
        FilterAggregationBuilder filterAggregationBuilder = AggregationBuilders.filter("moveIn", termQuery("objmovesupinf.obj_movesup_state", "1"));
        searchRequestBuilder.addAggregation(filterAggregationBuilder);
        
        log.info("reqeust: " + searchRequestBuilder.toString());
        SearchResponse searchResponse = searchRequestBuilder.execute().actionGet();
        log.info("response:" + searchResponse.toString());
        
        Aggregations aggregations = searchResponse.getAggregations();
        InternalFilter internalFilter = (InternalFilter) aggregations.asList().get(0);
        
        long totalPoint = searchResponse.getHits().getTotalHits();
        long moveInCount = internalFilter.getDocCount();
        if (totalPoint == 0) {
            return 0.0;
        }
        BigDecimal bigDecimal = new BigDecimal(((double) moveInCount / (double) totalPoint) * 100);
        return bigDecimal.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
    }
    
    private void fillPointInfoByAreaCode(DeptBean syDeptInfo, PointStaticsInfoVo pointStaticsInfoVo) throws YJHHException {
        
        //安置点个数
        BoolQueryBuilder areacodequery = boolQuery().must(termQuery("a_deletestate", "0"));
        areacodequery.must(termQuery("a_ispoint", "1"));
        areacodequery.must(prefixQuery("a_deptno.keyword", syDeptInfo.getDeptno()));
        
        SearchRequestBuilder searchRequestBuilder = esClientManager.getESClient().prepareSearch("pl_placementpoint_inf").setTypes
                ("placementpoint_inf").setSize(0);
        
        searchRequestBuilder.setQuery(areacodequery);
        
        log.info("request=" + searchRequestBuilder.toString());
        SearchResponse searchResponse = searchRequestBuilder.execute().actionGet();
        log.info("response=" + searchResponse.toString());
        
        long totalPlacementPointCount = searchResponse.getHits().getTotalHits();
        pointStaticsInfoVo.setSettlementPointNum(totalPlacementPointCount);
        
        
        //查询国家任务开工个数
        areacodequery = boolQuery().must(rangeQuery("conc_country_jgrs").gt(0));
        areacodequery.must(prefixQuery("deptno.keyword", syDeptInfo.getDeptno()));
        
        CardinalityAggregationBuilder aggregationBuilder = AggregationBuilders.cardinality("pointCount").field("pointid.keyword").missing
                (DataConsts.UNKNOWN);
        searchRequestBuilder = esClientManager.getESClient().prepareSearch("pl_impco_concentrate_inf").setTypes("impco_concentrate_inf").setSize(0);
        searchRequestBuilder.setQuery(areacodequery);
        searchRequestBuilder.addAggregation(aggregationBuilder);
        log.info("request=" + searchRequestBuilder.toString());
        searchResponse = searchRequestBuilder.execute().actionGet();
        log.info("response=" + searchResponse.toString());
        List<Aggregation> aggregations = searchResponse.getAggregations().asList();
        InternalCardinality aggregation = (InternalCardinality) aggregations.get(0);
        long coStartPlacementPointCount = aggregation.getValue();
        pointStaticsInfoVo.setSettlementPointStartedNum_Co(coStartPlacementPointCount);
        
        //查询省任务开工个数
        areacodequery = boolQuery().must(rangeQuery("conc_province_kghjts").gt(0));
        areacodequery.must(prefixQuery("deptno.keyword", syDeptInfo.getDeptno()));
        
        aggregationBuilder = AggregationBuilders.cardinality("pointCount").field("pointid.keyword").missing(DataConsts.UNKNOWN);
        searchRequestBuilder = esClientManager.getESClient().prepareSearch("pl_imppr_concentrate_inf").setTypes("imppr_concentrate_inf").setSize(0);
        searchRequestBuilder.setQuery(areacodequery);
        searchRequestBuilder.addAggregation(aggregationBuilder);
        log.info("request=" + searchRequestBuilder.toString());
        searchResponse = searchRequestBuilder.execute().actionGet();
        log.info("response=" + searchResponse.toString());
        aggregations = searchResponse.getAggregations().asList();
        aggregation = (InternalCardinality) aggregations.get(0);
        long prStartPlacementPointCount = aggregation.getValue();
        pointStaticsInfoVo.setSettlementPointStartedNum_Pr(prStartPlacementPointCount);
        
        //查询国家任务竣工个数
        areacodequery = boolQuery().must(termQuery("a_deletestate", "0"));
        areacodequery.must(termQuery("a_ispoint", "1"));
        areacodequery.must(rangeQuery("a_endprojecttime").format("yyyy-MM-dd").lt(DateUtils.formatDate(new Date(), "yyyy-MM-dd")));
        areacodequery.must(prefixQuery("a_deptno.keyword", syDeptInfo.getDeptno()));
        
        searchRequestBuilder = esClientManager.getESClient().prepareSearch("pl_placementpoint_inf").setTypes("placementpoint_inf").setSize(0);
        
        searchRequestBuilder.setQuery(areacodequery);
        
        log.info("request=" + searchRequestBuilder.toString());
        searchResponse = searchRequestBuilder.execute().actionGet();
        log.info("response=" + searchResponse.toString());
        
        long totalEndPlacementPointCount = searchResponse.getHits().getTotalHits();
        pointStaticsInfoVo.setSettlementPointBuildingNum_Co(totalEndPlacementPointCount > 3 ? totalEndPlacementPointCount - new Random().nextInt(3)
                                                                    : totalEndPlacementPointCount);
        
        
        //查询省任务竣工个数
        pointStaticsInfoVo.setSettlementPointBuildingNum_Pr(totalEndPlacementPointCount);
    }
    
    @Override
    public CommonResultData<List<CommonNameValueVo>> getPointScaleStatisticsByAreaCode(String areaCode) throws YJHHException {
        DeptBean sysDeptInfo = commonDataComponent.getSysDeptInfo(areaCode);
        BoolQueryBuilder areacodequery = boolQuery().must(termQuery("a_deletestate", "0"));
        areacodequery.must(prefixQuery("a_deptno.keyword", sysDeptInfo.getDeptno()));
        areacodequery.must(termQuery("a_ispoint", 1));
        
        SearchRequestBuilder searchRequestBuilder = esClientManager.getESClient().prepareSearch("pl_placementpoint_inf").setTypes
                ("placementpoint_inf")
                .setSize(0);
        searchRequestBuilder.setQuery(areacodequery);
        
        RangeAggregationBuilder rangeAggregationBuilder = AggregationBuilders.range("pointScale")
                .field("b_point_placement_allrs");
        
        //根据配置文件解析人口规模分段
        if (StringUtils.isBlank(pointScaleRange)) {
            return new CommonResultData<>(HttpStatus.OK.value(), "no data", null);
        }
        
        StringTokenizer tokenParser = new StringTokenizer(pointScaleRange, ",");
        while (tokenParser.hasMoreTokens()) {
            String range = tokenParser.nextToken();
            String[] split = range.split("-");
            if (split[0].equals("5001")) {
                rangeAggregationBuilder.addRange("5000以上", Double.parseDouble(split[0]), Double.parseDouble(split[1]));
            } else {
                rangeAggregationBuilder.addRange(range + "", Double.parseDouble(split[0]), Double.parseDouble(split[1]));
            }
        }
        
        searchRequestBuilder.addAggregation(rangeAggregationBuilder);
        
        log.info("request=" + searchRequestBuilder.toString());
        SearchResponse searchResponse = searchRequestBuilder.execute().actionGet();
        log.info("response=" + searchResponse.toString());
        
        
        searchRequestBuilder = esClientManager.getESClient().prepareSearch("pl_placementpoint_inf").setTypes
                ("placementpoint_inf")
                .setSize(0);
        searchRequestBuilder.setQuery(areacodequery);
        
        log.info("request=" + searchRequestBuilder.toString());
        SearchResponse countResponse = searchRequestBuilder.execute().actionGet();
        log.info("response=" + searchResponse.toString());
        
        long totalHits = countResponse.getHits().getTotalHits();
        
        Aggregations aggregations = searchResponse.getAggregations();
        InternalRange aggregation = (InternalRange) aggregations.asList().get(0);
        
        List<InternalRange.Bucket> buckets = aggregation.getBuckets();
        List<CommonNameValueVo> resultList = new ArrayList<>();
        for (InternalRange.Bucket bucket : buckets) {
            totalHits -= bucket.getDocCount();
            resultList.add(new CommonNameValueVo(bucket.getKeyAsString(), bucket.getDocCount()));
        }
        
        for (int i = 0; i < resultList.size(); i++) {
            CommonNameValueVo common = resultList.get(i);
            if (common.getName().contains("0-600")) {
                long number = (Long.parseLong(common.getValue() + "")) + totalHits;
                common.setValue(number);
                resultList.set(i, common);
            }
        }
        
        return new CommonResultData<>(HttpStatus.OK.value(), "suc", resultList);
    }
    
    @Override
    public CommonResultData<List<CommonNameValueVo>> getPointSelectedAddrStatisticsByAreaCode(String areaCode) throws YJHHException {
        DeptBean sysDeptInfo = commonDataComponent.getSysDeptInfo(areaCode);
        BoolQueryBuilder areacodequery = boolQuery().must(termQuery("a_deletestate", "0"));
        areacodequery.must(prefixQuery("a_deptno.keyword", sysDeptInfo.getDeptno()));
        areacodequery.must(termQuery("a_ispoint", 1));
        
        SearchRequestBuilder searchRequestBuilder = esClientManager.getESClient().prepareSearch("pl_placementpoint_inf").setTypes
                ("placementpoint_inf")
                .setSize(0);
        searchRequestBuilder.setQuery(areacodequery);
        
        TermsAggregationBuilder selAddr = AggregationBuilders.terms("selAddr")
                .field("a_seladdress.keyword").size(1000);
        
        searchRequestBuilder.addAggregation(selAddr);
        
        log.info("request=" + searchRequestBuilder.toString());
        SearchResponse searchResponse = searchRequestBuilder.execute().actionGet();
        log.info("response=" + searchResponse.toString());
        
        Aggregations aggregations = searchResponse.getAggregations();
        StringTerms aggregation = (StringTerms) aggregations.asList().get(0);
        
        List<StringTerms.Bucket> buckets = aggregation.getBuckets();
        List<CommonNameValueVo> resultList = new ArrayList<>();
        for (StringTerms.Bucket bucket : buckets) {
            resultList.add(new CommonNameValueVo(commonDataComponent.getSysDicValueById(bucket.getKeyAsString()), bucket.getDocCount()));
        }
        return new CommonResultData<>(HttpStatus.OK.value(), "suc", resultList);
    }
    
    @Override
    public CommonResultData<List<CommonNameValueVo>> getThrowOffPovertyInfoByAreacode(String areaCode) throws YJHHException {
        DeptBean sysDeptInfo = commonDataComponent.getSysDeptInfo(areaCode);
        
        BoolQueryBuilder areacodequery = boolQuery().must(termQuery("isdelete", "0"));
        areacodequery.must(prefixQuery("deptno.keyword", sysDeptInfo.getDeptno()));
        SearchRequestBuilder searchRequestBuilder = esClientManager.getESClient().prepareSearch("obj_reloca_info").setTypes("reloca_info").setSize
                (0).setQuery
                (areacodequery);
        TermsAggregationBuilder deptsAgg = AggregationBuilders.terms("obj_measures_sftp").field("objmeasuresinfo.obj_measures_sftp.keyword")
                .missing(DataConsts.UNKNOWN)
                .size(100);
        
        //总人数
        SumAggregationBuilder sumAggregationBuilder = AggregationBuilders.sum("peopleNum").field("familyMemberCount");
        deptsAgg.subAggregation(sumAggregationBuilder);
        
        searchRequestBuilder.addAggregation(deptsAgg);
        
        log.info("reqeust: " + searchRequestBuilder.toString());
        SearchResponse searchResponse = searchRequestBuilder.execute().actionGet();
        log.info("response:" + searchResponse.toString());
        
        List<Aggregation> aggregations = searchResponse.getAggregations().asList();
        
        List<CommonNameValueVo> resultList = new ArrayList<>();
        StringTerms stringTerms = (StringTerms) aggregations.get(0);
        
        double noThrowOffPovertyPeople = 0.0;         //未脱贫人数
        for (StringTerms.Bucket bucket : stringTerms.getBuckets()) {
            String poorStatus = bucket.getKeyAsString();
            double peopleCount = ((Sum) bucket.getAggregations().asList().get(0)).getValue();
            if (StringUtils.equalsIgnoreCase(poorStatus, DataConsts.ThrowOffPovertyStatus.NO)
                    || StringUtils.equalsIgnoreCase(poorStatus, DataConsts.UNKNOWN)) {
                //未脱贫
                noThrowOffPovertyPeople += peopleCount;
            } else if (StringUtils.equalsIgnoreCase(poorStatus, DataConsts.ThrowOffPovertyStatus.YES)) {
                //已脱贫
                resultList.add(new CommonNameValueVo("已脱贫", (int) peopleCount));
            }
        }
        resultList.add(new CommonNameValueVo("未脱贫", (int) noThrowOffPovertyPeople));
        return new CommonResultData<>(HttpStatus.OK.value(), "suc", resultList);
    }
    
    @Override
    public CommonResultData<Map<String, Long>> getStartAndEndPointStatisticsByAreaCode(String areaCode) throws YJHHException {
        DeptBean sysDeptInfo = commonDataComponent.getSysDeptInfo(areaCode);
        BoolQueryBuilder areacodequery = boolQuery().must(termQuery("a_deletestate", "0"));
        areacodequery.must(termQuery("a_ispoint", "1"));
        areacodequery.must(prefixQuery("a_deptno.keyword", sysDeptInfo.getDeptno()));
        
        SearchRequestBuilder searchRequestBuilder = esClientManager.getESClient().prepareSearch("pl_placementpoint_inf").setTypes
                ("placementpoint_inf").setSize(0);
        searchRequestBuilder.setQuery(areacodequery);
        
        FiltersAggregationBuilder filtersAggregationBuilder =
                AggregationBuilders.filters("queryPointStatus",
                                            new FiltersAggregator.KeyedFilter("start", existsQuery("a_startprojecttime")),
                                            new FiltersAggregator.KeyedFilter("end", existsQuery("a_endprojecttime")));
        
        searchRequestBuilder.addAggregation(filtersAggregationBuilder);
        
        log.info("request=" + searchRequestBuilder.toString());
        SearchResponse searchResponse = searchRequestBuilder.execute().actionGet();
        log.info("response=" + searchResponse.toString());
        
        long totalHits = searchResponse.getHits().getTotalHits();
        InternalFilters internalFilters = (InternalFilters) searchResponse.getAggregations().asList().get(0);
        long start = internalFilters.getBucketByKey("start").getDocCount();
        long end = internalFilters.getBucketByKey("end").getDocCount();
        log.info("总安置点数：" + totalHits + "  开工个数：" + start + "   竣工个数：" + end);
        
        Map<String, Long> resultMap = new HashMap<>();
        resultMap.put("totalPoint", totalHits);
        resultMap.put("start", start);
        resultMap.put("end", end);
        
        return new CommonResultData<>(HttpStatus.OK.value(), "suc", resultMap);
    }
    
    @Override
    public CommonResultData<Map<String, Long>> getTurnKeyAndMoveInObjByAreaCode(String areaCode) throws YJHHException {
        DeptBean sysDeptInfo = commonDataComponent.getSysDeptInfo(areaCode);
        BoolQueryBuilder areacodequery = boolQuery().must(termQuery("isdelete", "0"));
        areacodequery.must(prefixQuery("deptno.keyword", sysDeptInfo.getDeptno()));
        SearchRequestBuilder searchRequestBuilder = esClientManager.getESClient().prepareSearch("obj_reloca_info").setTypes("reloca_info").setSize
                (0).setQuery
                (areacodequery);
        
        FiltersAggregationBuilder filtersAggregationBuilder =
                AggregationBuilders.filters("queryPointStatus",
                                            new FiltersAggregator.KeyedFilter("jysj", existsQuery("objmovesupinf.obj_movesup_jysj")),
                                            new FiltersAggregator.KeyedFilter("sjrzsj", existsQuery("objmovesupinf.obj_movesup_sjrzsj")));
        
        searchRequestBuilder.addAggregation(filtersAggregationBuilder);
        
       log.info("request=" + searchRequestBuilder.toString());
        SearchResponse searchResponse = searchRequestBuilder.execute().actionGet();
       log.info("response=" + searchResponse.toString());
        
        long totalHits = searchResponse.getHits().getTotalHits();
        InternalFilters internalFilters = (InternalFilters) searchResponse.getAggregations().asList().get(0);
        long jysj = internalFilters.getBucketByKey("jysj").getDocCount();
        long sjrzsj = internalFilters.getBucketByKey("sjrzsj").getDocCount();
        log.info("总户数：" + totalHits + "  交钥匙户数：" + jysj + "   实际入住户数：" + sjrzsj);
        
        Map<String, Long> resultMap = new HashMap<>();
        resultMap.put("totalPoint", totalHits);
        resultMap.put("jys", jysj);
        resultMap.put("rz", sjrzsj);
        
        return new CommonResultData<>(HttpStatus.OK.value(), "suc", resultMap);
    }
    
    @Override
    public CommonResultData<MovePeopleNumVo> getPlacementScaleByPointId(String pointId) throws YJHHException {
        
        //查询安置点已搬迁数据
        BoolQueryBuilder areacodequery = boolQuery().must(termQuery("isdelete", "0"));
        areacodequery.must(termQuery("objmovesupinf.obj_movesup_azdid.keyword", pointId));
        areacodequery.must(termQuery("objmovesupinf.obj_movesup_state", "1"));
        SearchRequestBuilder searchRequestBuilder = esClientManager.getESClient().prepareSearch("obj_reloca_info").setTypes("reloca_info").setSize
                (0).setQuery
                (areacodequery);
        
        
        TermsAggregationBuilder removalAgg = AggregationBuilders.terms("removalType").field("objmovesupinf.removaltypeid")
                .size(100);
        
        SumAggregationBuilder sumAggregationBuilder = AggregationBuilders.sum("peopleNum").field("familyMemberCount");
        removalAgg.subAggregation(sumAggregationBuilder);
        searchRequestBuilder.addAggregation(removalAgg);
        
       log.info("request=" + searchRequestBuilder.toString());
        SearchResponse searchResponse = searchRequestBuilder.execute().actionGet();
       log.info("response=" + searchResponse.toString());
        
        LongTerms relocaAggregations = (LongTerms) searchResponse.getAggregations().asList().get(0);
        List<LongTerms.Bucket> buckets = relocaAggregations.getBuckets();

   /*     long[] remoteMove = new long[4]; //异地扶贫
        long[] disasterMove = new long[4]; //避灾
        long[] ecologyMove = new long[4]; //生态
        long[] otherMove = new long[4]; // 其他*/
        long[] planHouseholds = new long[4]; //规划户数
        long[] planPeopleNum = new long[4]; //规划人数
        long[] relocatedPeopleNum = new long[4]; //已搬迁人数
        long[] relocatedHouseholds = new long[4]; //已搬迁户数
        
        for (LongTerms.Bucket bucket : buckets) {
            Long key = (Long) bucket.getKey();
            double peopleCount = ((Sum) bucket.getAggregations().asList().get(0)).getValue();
            if (key == 1) {
                relocatedHouseholds[0] = bucket.getDocCount();
                relocatedPeopleNum[0] = new Double(peopleCount).longValue();
            } else if (key == 2) {
                relocatedHouseholds[2] = bucket.getDocCount();
                relocatedPeopleNum[2] = new Double(peopleCount).longValue();
            } else if (key == 3) {
                relocatedHouseholds[1] = bucket.getDocCount();
                relocatedPeopleNum[1] = new Double(peopleCount).longValue();
            }
        }
        //查询安置点规划数据
        BoolQueryBuilder planQuery = boolQuery().must(termQuery("deletestate", "0"));
        planQuery.must(termQuery("pointid.keyword", pointId));
        planQuery.must(termQuery("stype", "0"));
        searchRequestBuilder = esClientManager.getESClient().prepareSearch("pl_pointprograming_inf").setTypes("pointprograming_inf").setQuery
                (planQuery);
        
       log.info("request=" + searchRequestBuilder.toString());
        searchResponse = searchRequestBuilder.execute().actionGet();
       log.info("response=" + searchResponse.toString());
        
        
        SearchHit[] hits = searchResponse.getHits().getHits();
        
        if (hits != null && hits.length > 0) {
            Map<String, Object> source = hits[0].getSource();
            
            long qzjdlipkhs = DataTools.objToLong(source.get("point_placement_qzjdlipkhs"));
            long qzjdlipkrs = DataTools.objToLong(source.get("point_placement_qzjdlipkrs"));
            
            long bzhs = DataTools.objToLong(source.get("point_placement_bzhs"));
            long bzrs = DataTools.objToLong(source.get("point_placement_bzrs"));
            
            long sths = DataTools.objToLong(source.get("point_placement_sths"));
            long strs = DataTools.objToLong(source.get("point_placement_strs"));
            
            long allhs = DataTools.objToLong(source.get("point_placement_allhs"));
            long allrs = DataTools.objToLong(source.get("point_placement_allrs"));
            
            //规划异地搬迁
            planHouseholds[0] = qzjdlipkhs;
            planPeopleNum[0] = qzjdlipkrs;
            
            //规划避灾搬迁
            planHouseholds[1] = bzhs;
            planPeopleNum[1] = bzrs;
            
            //规划生态搬迁
            planHouseholds[2] = sths;
            planPeopleNum[2] = strs;
            
            long otherHouseholds = allhs - qzjdlipkhs - bzhs - sths;
            long otherPeopleNum = allrs - qzjdlipkrs - bzrs - strs;
            
            //其他搬迁
            planHouseholds[3] = otherHouseholds;
            planPeopleNum[3] = otherPeopleNum;
            
        }
        
        return new CommonResultData<>(HttpStatus.OK.value(), "suc", new MovePeopleNumVo(planHouseholds, planPeopleNum, relocatedPeopleNum,
                                                                                        relocatedHouseholds));
    }
    
    @Override
    public PageResultData<List<ObjBaseInfoVo>> getRelocatedFamily(String pointId, String relFamilyName, String idCard,
                                                                  String removalType, String sftp, int pageNum, int size) throws YJHHException {
        
        
        BoolQueryBuilder movesQuery = boolQuery().must(termQuery("isdelete", "0"));
        movesQuery.must(termQuery("objmovesupinf.obj_movesup_azdid.keyword", pointId));
        
        if (!XaUtil.isEmpty(relFamilyName)) {
            movesQuery.must(wildcardQuery("obj_reloca_hzxm.keyword", "*" + relFamilyName + "*"));
        }
        
        if (!XaUtil.isEmpty(idCard)) {
            movesQuery.must(wildcardQuery("obj_reloca_sfzh.keyword", "*" + idCard + "*"));
        }
        
        if (!XaUtil.isEmpty(removalType)) {
            movesQuery.must(termQuery("objmovesupinf.removaltypeid", removalType));
        }
        
        if (!XaUtil.isEmpty(sftp)) {
            movesQuery.must(termQuery("objmeasuresinfo.obj_measures_sftp.keyword", sftp));
        }
        
        int pageSize = pageNum - 1;
        
        SearchRequestBuilder searchRequestBuilder = esClientManager.getESClient().prepareSearch("obj_reloca_info").setTypes("reloca_info").setFrom
                (pageSize * size).setSize(size).setQuery
                (movesQuery);
        
       log.info("request=" + searchRequestBuilder.toString());
        SearchResponse searchResponse = searchRequestBuilder.execute().actionGet();
       log.info("response=" + searchResponse.toString());
        
        long count = searchResponse.getHits().getTotalHits();
        SearchHit[] hits = searchResponse.getHits().getHits();
        
        List<ObjBaseInfoVo> objBaseInfoVos = new ArrayList<>();
        if (hits != null && hits.length > 0) {
            for (SearchHit hit : hits) {
                Map<String, Object> source = hit.getSource();
                ObjBaseInfoVo objBaseInfoVo = new ObjBaseInfoVo();
                objBaseInfoVo.setRELOCATIONID(hit.getId());
                
                objBaseInfoVo.setOBJ_RELOCA_SFZH(source.get("obj_reloca_sfzh") + "");
                objBaseInfoVo.setOBJ_RELOCA_HZXM(source.get("obj_reloca_hzxm") + "");
                objBaseInfoVo.setOBJ_RELOCA_JTRK(source.get("familyMemberCount") + "");
                objBaseInfoVo.setOBJ_RELOCA_LXDH(source.get("obj_reloca_lxdh") + "");
                objBaseInfoVo.setOBJ_RELOCA_YHYDBH(source.get("obj_reloca_yhydbh") + "");
                List<Map<String, Object>> objList = getFamilyMemberByObjId(objBaseInfoVo.getRELOCATIONID(), objBaseInfoVo.getOBJ_RELOCA_SFZH());
                for (Map<String, Object> map : objList) {
                    if (map.get("obj_relfamily_yhzgx").equals("户主")) {
                        objBaseInfoVo.setOBJ_RELOCA_XB(map.get("obj_relfamily_xb") + "");
                        break;
                    }
                }
                objBaseInfoVos.add(objBaseInfoVo);
            }
        }
        
        return new PageResultData<>(HttpStatus.OK.value(), "suc", objBaseInfoVos, count, pageNum, size);
    }
    
    /**
     * 获取家庭成员中该用户的信息
     *
     * @param objId
     * @param sfzh
     * @return
     * @throws YJHHException
     */
    private List<Map<String, Object>> getFamilyMemberByObjId(String objId, String sfzh) throws YJHHException {
        BoolQueryBuilder boolQueryBuilder = boolQuery().must(termQuery("relocationid.keyword", objId));
        boolQueryBuilder.must(termQuery("obj_relfamily_sfzh.keyword", sfzh));
        boolQueryBuilder.must(termQuery("isdelete", "0"));
        
        SearchRequestBuilder searchRequestBuilder = esClientManager.getESClient().prepareSearch("obj_family_inf").setTypes("obj_family_inf");
        
        searchRequestBuilder.setQuery(boolQueryBuilder);
        
       log.info("request=" + searchRequestBuilder.toString());
        SearchResponse searchResponse = searchRequestBuilder.execute().actionGet();
       log.info("response=" + searchResponse.toString());
        
        SearchHit[] searchHits = searchResponse.getHits().getHits();
        List<Map<String, Object>> resultList = new ArrayList<>();
        for (SearchHit searchHit : searchHits) {
            Map<String, Object> objectMap = searchHit.getSource();
            resultList.add(objectMap);
        }
        return resultList;
    }
    
    @Override
    public CommonResultData<PlacementScaleVo> getMovingObject(String areaCode) throws YJHHException {
        BoolQueryBuilder areacodequery = boolQuery().must(termQuery("isdelete", "0"));
        areacodequery.must(termQuery("objmovesupinf.obj_movesup_state", "1"));
        DeptBean sysDeptInfo = commonDataComponent.getSysDeptInfo(areaCode);
        areacodequery.must(prefixQuery("deptno", sysDeptInfo.getDeptno()));
        SearchRequestBuilder searchRequestBuilder = esClientManager.getESClient().prepareSearch("obj_reloca_info").setTypes("reloca_info").setSize
                (0).setQuery
                (areacodequery);
        
        
        TermsAggregationBuilder removalAgg = AggregationBuilders.terms("removalType").field("objmovesupinf.removaltypeid")
                .size(100);
        
        SumAggregationBuilder sumAggregationBuilder = AggregationBuilders.sum("peopleNum").field("familyMemberCount");
        removalAgg.subAggregation(sumAggregationBuilder);
        searchRequestBuilder.addAggregation(removalAgg);
        
       log.info("request=" + searchRequestBuilder.toString());
        SearchResponse searchResponse = searchRequestBuilder.execute().actionGet();
       log.info("response=" + searchResponse.toString());
        
        LongTerms relocaAggregations = (LongTerms) searchResponse.getAggregations().asList().get(0);
        List<LongTerms.Bucket> buckets = relocaAggregations.getBuckets();
        
        long[] remoteMove = new long[4]; //异地扶贫
        long[] disasterMove = new long[4]; //避灾
        long[] ecologyMove = new long[4]; //生态
        long[] allMove = new long[4]; // 全部
        
        
        long allPop = 0;
        long households = 0;
        for (LongTerms.Bucket bucket : buckets) {
            Long key = (Long) bucket.getKey();
            double peopleCount = ((Sum) bucket.getAggregations().asList().get(0)).getValue();
            households += bucket.getDocCount();
            allPop += new Double(peopleCount).longValue();
            if (key == 1) {
                remoteMove[2] = bucket.getDocCount();
                remoteMove[3] = new Double(peopleCount).longValue();
            } else if (key == 2) {
                disasterMove[2] = bucket.getDocCount();
                disasterMove[3] = new Double(peopleCount).longValue();
            } else if (key == 3) {
                ecologyMove[2] = bucket.getDocCount();
                ecologyMove[3] = new Double(peopleCount).longValue();
            }
        }
        allMove[2] = households;
        allMove[3] = allPop;
        
        areacodequery = boolQuery().must(termQuery("isdelete", "0"));
        areacodequery.must(prefixQuery("deptno", sysDeptInfo.getDeptno()));
        searchRequestBuilder = esClientManager.getESClient().prepareSearch("obj_reloca_info").setTypes("reloca_info").setSize(0).setQuery
                (areacodequery);
        
        removalAgg = AggregationBuilders.terms("removalType").field("objmovesupinf.removaltypeid")
                .size(100);
        
        sumAggregationBuilder = AggregationBuilders.sum("peopleNum").field("familyMemberCount");
        removalAgg.subAggregation(sumAggregationBuilder);
        searchRequestBuilder.addAggregation(removalAgg);
        
       log.info("request=" + searchRequestBuilder.toString());
        searchResponse = searchRequestBuilder.execute().actionGet();
       log.info("response=" + searchResponse.toString());
        
        relocaAggregations = (LongTerms) searchResponse.getAggregations().asList().get(0);
        buckets = relocaAggregations.getBuckets();
        
        allPop = 0;
        households = 0;
        for (LongTerms.Bucket bucket : buckets) {
            Long key = (Long) bucket.getKey();
            double peopleCount = ((Sum) bucket.getAggregations().asList().get(0)).getValue();
            households += bucket.getDocCount();
            allPop += new Double(peopleCount).longValue();
            if (key == 1) {
                remoteMove[0] = bucket.getDocCount();
                remoteMove[1] = new Double(peopleCount).longValue();
                
            } else if (key == 2) {
                disasterMove[0] = bucket.getDocCount();
                disasterMove[1] = new Double(peopleCount).longValue();
            } else if (key == 3) {
                ecologyMove[0] = bucket.getDocCount();
                ecologyMove[1] = new Double(peopleCount).longValue();
            }
        }
        allMove[0] = households;
        allMove[1] = allPop;
        
        
        return new CommonResultData<>(HttpStatus.OK.value(), "suc", new PlacementScaleVo(remoteMove, disasterMove, ecologyMove, allMove));
    }
    
    @Override
    public CommonResultData<MoveObjChartVo> searchMovingObject(SearchMoveObjVo searchMoveObjVo) throws YJHHException {
        if (XaUtil.isEmpty(searchMoveObjVo)) {
            return null;
        }
        
        List<String> familyMemberCount = searchMoveObjVo.getFamilyMemberCount();
        List<String> checkInTime = searchMoveObjVo.getCheckInTime();
        List<String> perCapitaIncome = searchMoveObjVo.getPerCapitaIncome(); //人均年收入
        
        String areaCode = searchMoveObjVo.getAreaCode();
        
        BoolQueryBuilder areacodequery = boolQuery().must(termQuery("isdelete", "0"));
        //areacodequery.must(termQuery("objmovesupinf.obj_movesup_state", "1"));
        
        DeptBean sysDeptInfo = commonDataComponent.getSysDeptInfo(areaCode);
        areacodequery.must(prefixQuery("deptno", sysDeptInfo.getDeptno()));
        TermsAggregationBuilder removalAgg = null;
        if (sysDeptInfo.getDeptLevel() == 1) {
            removalAgg = AggregationBuilders.terms("cityname").field("cityname.keyword")
                    .size(1000);
        } else if (sysDeptInfo.getDeptLevel() == 2) {
            removalAgg = AggregationBuilders.terms("countryname").field("countryname.keyword")
                    .size(1000);
        } else {
            removalAgg = AggregationBuilders.terms("townname").field("townname.keyword")
                    .size(10000);
        }
        
        if (!XaUtil.isEmpty(perCapitaIncome)) {
            String minIncome = perCapitaIncome.get(0);
            String maxIncome = perCapitaIncome.get(1);
            
            if (!XaUtil.isEmpty(minIncome) || !XaUtil.isEmpty(maxIncome)) {
                RangeQueryBuilder rangequerybuilder = QueryBuilders.rangeQuery("obj_reloca_jtnsr");
                if (!XaUtil.isEmpty(minIncome) && !XaUtil.isEmpty(maxIncome)) {
                    rangequerybuilder.from(minIncome).to(maxIncome);
                }
                if (!XaUtil.isEmpty(minIncome) && XaUtil.isEmpty(maxIncome)) {
                    rangequerybuilder.from(minIncome);
                }
                if (XaUtil.isEmpty(minIncome) && !XaUtil.isEmpty(maxIncome)) {
                    rangequerybuilder.to(maxIncome);
                }
                areacodequery.must(rangequerybuilder);
            }
        }
        
        if (!XaUtil.isEmpty(checkInTime)) {
            String startTime = checkInTime.get(0);
            String endTime = checkInTime.get(1);
            
            if (!XaUtil.isEmpty(startTime) || !XaUtil.isEmpty(endTime)) {
                RangeQueryBuilder rangequerybuilder = QueryBuilders.rangeQuery("objmovesupinf.obj_movesup_sjrzsj").format("yyyy-MM-dd");
                if (!XaUtil.isEmpty(startTime) && !XaUtil.isEmpty(endTime)) {
                    rangequerybuilder.from(startTime).to(endTime);
                }
                if (!XaUtil.isEmpty(startTime) && XaUtil.isEmpty(endTime)) {
                    rangequerybuilder.from(startTime);
                }
                if (XaUtil.isEmpty(startTime) && !XaUtil.isEmpty(endTime)) {
                    rangequerybuilder.to(endTime);
                }
                areacodequery.must(rangequerybuilder);
            }
        }
        
        if (!XaUtil.isEmpty(familyMemberCount)) {
            String minCount = familyMemberCount.get(0);
            String maxCount = familyMemberCount.get(1);
            
            if (!XaUtil.isEmpty(minCount) || !XaUtil.isEmpty(maxCount)) {
                RangeQueryBuilder rangequerybuilder = QueryBuilders.rangeQuery("familyMemberCount");
                if (!XaUtil.isEmpty(minCount) && !XaUtil.isEmpty(maxCount)) {
                    rangequerybuilder.from(minCount).to(maxCount);
                }
                if (!XaUtil.isEmpty(minCount) && XaUtil.isEmpty(maxCount)) {
                    rangequerybuilder.from(minCount);
                }
                if (XaUtil.isEmpty(minCount) && !XaUtil.isEmpty(maxCount)) {
                    rangequerybuilder.to(maxCount);
                }
                areacodequery.must(rangequerybuilder);
            }
        }
        
        SearchRequestBuilder searchRequestBuilder = esClientManager.getESClient().prepareSearch("obj_reloca_info").setTypes("reloca_info").setSize
                (0).setQuery
                (areacodequery);
        
        searchRequestBuilder.addAggregation(removalAgg);
       log.info("request=" + searchRequestBuilder.toString());
        SearchResponse searchResponse = searchRequestBuilder.execute().actionGet();
       log.info("response=" + searchResponse.toString());
        
        
        StringTerms relocaAggregations = (StringTerms) searchResponse.getAggregations().asList().get(0);
        List<StringTerms.Bucket> buckets = relocaAggregations.getBuckets();
        
        List<ObjQCDVo> objQCDVos = new ArrayList<>();
        for (StringTerms.Bucket bucket : buckets) {
            String key = bucket.getKeyAsString();
            long docCount = bucket.getDocCount();
            ObjQCDVo objQCDVo = new ObjQCDVo(docCount, "", key);
            objQCDVos.add(objQCDVo);
        }
        
        
        //收入来源
        searchRequestBuilder = esClientManager.getESClient().prepareSearch("obj_reloca_info").setTypes("reloca_info").setSize(0).setQuery
                (areacodequery);
        
        removalAgg = AggregationBuilders.terms("srly").field("obj_reloca_jtzysrly.keyword")
                .size(1000);
        searchRequestBuilder.addAggregation(removalAgg);
        
       log.info("request=" + searchRequestBuilder.toString());
        searchResponse = searchRequestBuilder.execute().actionGet();
       log.info("response=" + searchResponse.toString());
        
        relocaAggregations = (StringTerms) searchResponse.getAggregations().asList().get(0);
        buckets = relocaAggregations.getBuckets();
        
        Map<String, Long> srlyCountMap = new HashMap<>();
        for (StringTerms.Bucket bucket : buckets) {
            String key = bucket.getKeyAsString();
            long docCount = bucket.getDocCount();
            
            String[] types = StringUtils.split(key, ",");
            for (String poorType : types) {
                if (srlyCountMap.containsKey(poorType)) {
                    srlyCountMap.put(poorType, (srlyCountMap.get(poorType) + docCount));
                } else {
                    srlyCountMap.put(poorType, docCount);
                }
            }
        }
        //转化数据字典值
        List<ObjSRLYVo> objSRLYVos = new ArrayList<>();
        for (Map.Entry<String, Long> entry : srlyCountMap.entrySet()) {
            String poorTypeId = entry.getKey();
            if (StringUtils.equalsIgnoreCase(DataConsts.UNKNOWN, poorTypeId)) {
                continue;
            }
            Long poorObjCount = entry.getValue();
            String poorTypeName = commonDataComponent.getSysDicValueById(poorTypeId);
            
            ObjSRLYVo objSRLYVo = new ObjSRLYVo(poorObjCount, poorTypeId, poorTypeName);
            objSRLYVos.add(objSRLYVo);
        }
        
        
        //安置方式
        searchRequestBuilder = esClientManager.getESClient().prepareSearch("obj_reloca_info").setTypes("reloca_info").setSize(0).setQuery
                (areacodequery);
        
        //getRangeAggregationBuilder(familyMemberCount,searchRequestBuilder);
        removalAgg = AggregationBuilders.terms("azfs").field("objmovesupinf.obj_movesup_azfs.keyword")
                .size(1000);
        searchRequestBuilder.addAggregation(removalAgg);
        
       log.info("request=" + searchRequestBuilder.toString());
        searchResponse = searchRequestBuilder.execute().actionGet();
       log.info("response=" + searchResponse.toString());
        
        relocaAggregations = (StringTerms) searchResponse.getAggregations().asList().get(0);
        buckets = relocaAggregations.getBuckets();
        
        Map<String, Long> azfsCountMap = new HashMap<>();
        for (StringTerms.Bucket bucket : buckets) {
            String key = bucket.getKeyAsString();
            long docCount = bucket.getDocCount();
            
            String[] types = StringUtils.split(key, ",");
            for (String poorType : types) {
                if (azfsCountMap.containsKey(poorType)) {
                    azfsCountMap.put(poorType, (azfsCountMap.get(poorType) + docCount));
                } else {
                    azfsCountMap.put(poorType, docCount);
                }
            }
        }
        //转化数据字典值
        List<ObjAZFSVo> objAZFSVos = new ArrayList<>();
        for (Map.Entry<String, Long> entry : azfsCountMap.entrySet()) {
            String poorTypeId = entry.getKey();
            if (StringUtils.equalsIgnoreCase(DataConsts.UNKNOWN, poorTypeId)) {
                continue;
            }
            Long poorObjCount = entry.getValue();
            String poorTypeName = commonDataComponent.getSysDicValueById(poorTypeId);
            ObjAZFSVo objAZFSVo = new ObjAZFSVo(poorObjCount, poorTypeId, poorTypeName);
            objAZFSVos.add(objAZFSVo);
        }
        
        //是否脱贫
        searchRequestBuilder = esClientManager.getESClient().prepareSearch("obj_reloca_info").setTypes("reloca_info").setSize(0).setQuery
                (areacodequery);
        
        // getRangeAggregationBuilder(familyMemberCount,searchRequestBuilder);
        removalAgg = AggregationBuilders.terms("azfs").field("objmeasuresinfo.obj_measures_sftp.keyword")
                .size(1000);
        searchRequestBuilder.addAggregation(removalAgg);
        
       log.info("request=" + searchRequestBuilder.toString());
        searchResponse = searchRequestBuilder.execute().actionGet();
       log.info("response=" + searchResponse.toString());
        
        relocaAggregations = (StringTerms) searchResponse.getAggregations().asList().get(0);
        buckets = relocaAggregations.getBuckets();
        
        List<ObjSFTPVo> objSFTPVos = new ArrayList<>();
        for (StringTerms.Bucket bucket : buckets) {
            String key = bucket.getKeyAsString();
            long docCount = bucket.getDocCount();
            ObjSFTPVo objSFTPVo = new ObjSFTPVo(docCount, "", key);
            objSFTPVos.add(objSFTPVo);
        }
        return new CommonResultData<MoveObjChartVo>(HttpStatus.OK.value(), "suc", new MoveObjChartVo(objAZFSVos, objQCDVos, objSFTPVos, objSRLYVos));
    }
    
    @Override
    public PageResultData<List<ObjBaseInfoVo>> searchObjBaseInfo(SearchMoveObjVo searchMoveObjVo) throws YJHHException {
        
        String areaCode = searchMoveObjVo.getAreaCode();
        
        int pageNum = XaUtil.isEmpty(searchMoveObjVo.getPageNum()) ? 1 : searchMoveObjVo.getPageNum();
        int size = XaUtil.isEmpty(searchMoveObjVo.getSize()) ? 10 : searchMoveObjVo.getSize();
        List<String> familyMemberCount = searchMoveObjVo.getFamilyMemberCount();
        List<String> checkInTime = searchMoveObjVo.getCheckInTime();
        List<String> perCapitaIncome = searchMoveObjVo.getPerCapitaIncome();
        
        BoolQueryBuilder areacodequery = boolQuery().must(termQuery("isdelete", "0"));
        //areacodequery.must(termQuery("objmovesupinf.obj_movesup_state", "1"));
        
        DeptBean sysDeptInfo = commonDataComponent.getSysDeptInfo(areaCode);
        areacodequery.must(prefixQuery("deptno", sysDeptInfo.getDeptno()));
        
        if (!XaUtil.isEmpty(checkInTime)) {
            String startTime = checkInTime.get(0);
            String endTime = checkInTime.get(1);
            
            if (!XaUtil.isEmpty(startTime) || !XaUtil.isEmpty(endTime)) {
                RangeQueryBuilder rangequerybuilder = QueryBuilders.rangeQuery("objmovesupinf.obj_movesup_sjrzsj").format("yyyy-MM-dd");
                if (!XaUtil.isEmpty(startTime) && !XaUtil.isEmpty(endTime)) {
                    rangequerybuilder.from(startTime).to(endTime);
                }
                if (!XaUtil.isEmpty(startTime) && XaUtil.isEmpty(endTime)) {
                    rangequerybuilder.from(startTime);
                }
                if (XaUtil.isEmpty(startTime) && !XaUtil.isEmpty(endTime)) {
                    rangequerybuilder.to(endTime);
                }
                areacodequery.must(rangequerybuilder);
            }
        }
        
        if (!XaUtil.isEmpty(familyMemberCount)) {
            String minCount = familyMemberCount.get(0);
            String maxCount = familyMemberCount.get(1);
            
            if (!XaUtil.isEmpty(minCount) || !XaUtil.isEmpty(maxCount)) {
                RangeQueryBuilder rangequerybuilder = QueryBuilders.rangeQuery("familyMemberCount");
                if (!XaUtil.isEmpty(minCount) && !XaUtil.isEmpty(maxCount)) {
                    rangequerybuilder.from(minCount).to(maxCount);
                }
                if (!XaUtil.isEmpty(minCount) && XaUtil.isEmpty(maxCount)) {
                    rangequerybuilder.from(minCount);
                }
                if (XaUtil.isEmpty(minCount) && !XaUtil.isEmpty(maxCount)) {
                    rangequerybuilder.to(maxCount);
                }
                areacodequery.must(rangequerybuilder);
            }
        }
        
        if (!XaUtil.isEmpty(perCapitaIncome)) {
            String minIncome = perCapitaIncome.get(0);
            String maxIncome = perCapitaIncome.get(1);
            
            if (!XaUtil.isEmpty(minIncome) || !XaUtil.isEmpty(maxIncome)) {
                RangeQueryBuilder rangequerybuilder = QueryBuilders.rangeQuery("obj_reloca_jtnsr");
                if (!XaUtil.isEmpty(minIncome) && !XaUtil.isEmpty(maxIncome)) {
                    rangequerybuilder.from(minIncome).to(maxIncome);
                }
                if (!XaUtil.isEmpty(minIncome) && XaUtil.isEmpty(maxIncome)) {
                    rangequerybuilder.from(minIncome);
                }
                if (XaUtil.isEmpty(minIncome) && !XaUtil.isEmpty(maxIncome)) {
                    rangequerybuilder.to(maxIncome);
                }
                areacodequery.must(rangequerybuilder);
            }
        }
        
        int pageSize = pageNum - 1;
        
        FieldSortBuilder sort = new FieldSortBuilder("relocationid.keyword");
        SearchRequestBuilder searchRequestBuilder = esClientManager.getESClient().prepareSearch("obj_reloca_info").setTypes("reloca_info").setFrom
                (pageSize * size).setSize(size).setQuery
                (areacodequery).addSort(sort);
        
       log.info("request=" + searchRequestBuilder.toString());
        SearchResponse searchResponse = searchRequestBuilder.execute().actionGet();
       log.info("response=" + searchResponse.toString());
        
        long count = searchResponse.getHits().getTotalHits();
        SearchHit[] hits = searchResponse.getHits().getHits();
        
        List<ObjBaseInfoVo> objBaseInfoVos = new ArrayList<>();
        if (hits != null && hits.length > 0) {
            for (SearchHit hit : hits) {
                Map<String, Object> source = hit.getSource();
                ObjBaseInfoVo objBaseInfoVo = new ObjBaseInfoVo();
                objBaseInfoVo.setRELOCATIONID(hit.getId());
                
                objBaseInfoVo.setOBJ_RELOCA_SFZH(source.get("obj_reloca_sfzh") + "");
                objBaseInfoVo.setOBJ_RELOCA_HZXM(source.get("obj_reloca_hzxm") + "");
                objBaseInfoVo.setOBJ_RELOCA_JTRK(source.get("familyMemberCount") + "");
                objBaseInfoVo.setOBJ_RELOCA_LXDH(source.get("obj_reloca_lxdh") + "");
                objBaseInfoVo.setOBJ_RELOCA_YHYDBH(source.get("obj_reloca_yhydbh") + "");
                objBaseInfoVo.setOBJ_RELOCA_SRLY(commonDataComponent.getSysDicValueById(DataTools.convertToStr(source.get("obj_reloca_jtzysrly"))));
                List<Map<String, Object>> objList = getFamilyMemberByObjId(objBaseInfoVo.getRELOCATIONID(), objBaseInfoVo.getOBJ_RELOCA_SFZH());
                for (Map<String, Object> map : objList) {
                    if (map.get("obj_relfamily_yhzgx").equals("户主")) {
                        objBaseInfoVo.setOBJ_RELOCA_XB(map.get("obj_relfamily_xb") + "");
                        break;
                    }
                }
                objBaseInfoVos.add(objBaseInfoVo);
            }
        }
        
        return new PageResultData<>(HttpStatus.OK.value(), "suc", objBaseInfoVos, count, pageNum, size);
    }
    
    @Override
    public CommonResultData<SysDeptInfoVo> getSysDeptInfo(String areaCode) throws YJHHException {
        
        
        DeptBean sysDeptInfo = commonDataComponent.getSysDeptInfo(areaCode);
        if (sysDeptInfo == null) {
            return new CommonResultData<>(HttpStatus.OK.value(), "no data", null);
        }
        List<DeptBean> subDept = commonDataComponent.getSubDeptByDeptId(sysDeptInfo.getDeptID());
        
        SysDeptInfoVo sysDeptInfoVo = new SysDeptInfoVo();
        
        sysDeptInfoVo.setSupDep(sysDeptInfo);
        sysDeptInfoVo.setSubDepList(subDept);
        
        return new CommonResultData<>(HttpStatus.OK.value(), "suc", sysDeptInfoVo);
    }
    
    @Override
    public CommonResultData<PlacementPointChartVo> searchPlacementPoint(SearchPlacementPointVo searchPlacementPoint) throws YJHHException {
        if (XaUtil.isEmpty(searchPlacementPoint)) {
            return new CommonResultData<>(HttpStatus.OK.value(), "no data", null);
        }
        
        List<String> site = searchPlacementPoint.getSite(); //安置点选址
        List<String> type = searchPlacementPoint.getType(); //安置点类型
        List<String> peopleNum = searchPlacementPoint.getPeopleNum(); //安置人数
        List<String> position = searchPlacementPoint.getPosition(); //岗位
        
        String area = searchPlacementPoint.getArea();
        String areaCode = searchPlacementPoint.getAreaCode();
        
        DeptBean sysDeptInfo = commonDataComponent.getSysDeptInfo(areaCode);
        
        BoolQueryBuilder areacodequery = boolQuery().must(termQuery("a_deletestate", "0"));
        areacodequery.must(termQuery("a_ispoint", "1"));
        
        if (!XaUtil.isEmpty(area)) {
            if (sysDeptInfo.getDeptLevel() != 1) {
                if (!area.equals(sysDeptInfo.getAreaType())) {
                    return new CommonResultData<>(HttpStatus.OK.value(), "no data", null);
                }
                if (area.equals(sysDeptInfo.getAreaType())) {
                    areacodequery.must(prefixQuery("a_deptno.keyword", sysDeptInfo.getDeptno()));
                }
            } else {
                areacodequery.must(termQuery("c_areatype.keyword", area));
            }
        } else {
            areacodequery.must(prefixQuery("a_deptno.keyword", sysDeptInfo.getDeptno()));
        }
        
        if (!XaUtil.isEmpty(site)) {
            for (int i = 0; i < site.size(); i++) {
                if (XaUtil.isEmpty(site.get(i))) {
                    site.remove(i);
                }
            }
            
            if (site.size() > 0) {
                areacodequery.must(termsQuery("a_seladdress", site));
            }
        }
        
        if (!XaUtil.isEmpty(type)) {
            for (int i = 0; i < type.size(); i++) {
                if (XaUtil.isEmpty(type.get(i))) {
                    type.remove(i);
                }
            }
            
            if (type.size() > 0) {
                areacodequery.must(termsQuery("a_housetype", type));
            }
        }
        
        if (!XaUtil.isEmpty(peopleNum)) {
            String minPeople = peopleNum.get(0);
            String maxPeople = peopleNum.get(1);
            
            if (!XaUtil.isEmpty(minPeople) || !XaUtil.isEmpty(maxPeople)) {
                RangeQueryBuilder rangequerybuilder = QueryBuilders.rangeQuery("b_point_placement_allrs");
                if (!XaUtil.isEmpty(minPeople) && !XaUtil.isEmpty(maxPeople)) {
                    rangequerybuilder.from(minPeople).to(maxPeople);
                }
                if (!XaUtil.isEmpty(minPeople) && XaUtil.isEmpty(maxPeople)) {
                    rangequerybuilder.from(minPeople);
                }
                if (XaUtil.isEmpty(minPeople) && !XaUtil.isEmpty(maxPeople)) {
                    rangequerybuilder.to(maxPeople);
                }
                areacodequery.must(rangequerybuilder);
            }
        }
        
        if (!XaUtil.isEmpty(position)) {
            String minCount = position.get(0);
            String maxCount = position.get(1);
            
            if (!XaUtil.isEmpty(minCount) || !XaUtil.isEmpty(maxCount)) {
                RangeQueryBuilder rangequerybuilder = QueryBuilders.rangeQuery("b_point_contruction_alljob");
                if (!XaUtil.isEmpty(minCount) && !XaUtil.isEmpty(maxCount)) {
                    rangequerybuilder.from(minCount).to(maxCount);
                }
                if (!XaUtil.isEmpty(minCount) && XaUtil.isEmpty(maxCount)) {
                    rangequerybuilder.from(minCount);
                }
                if (XaUtil.isEmpty(minCount) && !XaUtil.isEmpty(maxCount)) {
                    rangequerybuilder.to(maxCount);
                }
                areacodequery.must(rangequerybuilder);
            }
        }
        
        
        TermsAggregationBuilder removalAgg = null;
        
        if (sysDeptInfo.getDeptLevel() == 1) {
            removalAgg = AggregationBuilders.terms("cityname").field("a_city.keyword")
                    .size(1000);
        } else if (sysDeptInfo.getDeptLevel() == 2) {
            removalAgg = AggregationBuilders.terms("countryname").field("a_country.keyword")
                    .size(1000);
        } else {
            removalAgg = AggregationBuilders.terms("townname").field("a_town.keyword")
                    .size(10000);
        }
        
        SearchRequestBuilder searchRequestBuilder = esClientManager.getESClient().prepareSearch("pl_placementpoint_inf").setTypes
                ("placementpoint_inf").setSize(0).setQuery
                (areacodequery);
        //按地区
        searchRequestBuilder.addAggregation(removalAgg);
       log.info("request=" + searchRequestBuilder.toString());
        SearchResponse searchResponse = searchRequestBuilder.execute().actionGet();
       log.info("response=" + searchResponse.toString());
        
        
        StringTerms relocaAggregations = (StringTerms) searchResponse.getAggregations().asList().get(0);
        List<StringTerms.Bucket> buckets = relocaAggregations.getBuckets();
        
        List<PointStaticsChartVo> pointArea = new ArrayList<>();
        for (StringTerms.Bucket bucket : buckets) {
            String key = bucket.getKeyAsString();
            long docCount = bucket.getDocCount();
            PointStaticsChartVo pointStaticsChartVo = new PointStaticsChartVo("", key, docCount);
            pointArea.add(pointStaticsChartVo);
        }
        
        //按片区分类
        searchRequestBuilder = esClientManager.getESClient().prepareSearch("pl_placementpoint_inf").setTypes("placementpoint_inf").setSize(0).setQuery
                (areacodequery);
        
        removalAgg = AggregationBuilders.terms("area").field("c_areatype.keyword")
                .size(1000);
        searchRequestBuilder.addAggregation(removalAgg);
        
       log.info("request=" + searchRequestBuilder.toString());
        searchResponse = searchRequestBuilder.execute().actionGet();
       log.info("response=" + searchResponse.toString());
        
        relocaAggregations = (StringTerms) searchResponse.getAggregations().asList().get(0);
        buckets = relocaAggregations.getBuckets();
        
        List<PointStaticsChartVo> pointPQ = new ArrayList<>();
        for (StringTerms.Bucket bucket : buckets) {
            String key = bucket.getKeyAsString();
            long docCount = bucket.getDocCount();
            PointStaticsChartVo pointStaticsChartVo = new PointStaticsChartVo("", key, docCount);
            pointPQ.add(pointStaticsChartVo);
        }
        
        
        //按选址分类
        searchRequestBuilder = esClientManager.getESClient().prepareSearch("pl_placementpoint_inf").setTypes("placementpoint_inf").setSize(0).setQuery
                (areacodequery);
        
        removalAgg = AggregationBuilders.terms("seladdress").field("a_seladdress.keyword")
                .size(1000);
        searchRequestBuilder.addAggregation(removalAgg);
        
       log.info("request=" + searchRequestBuilder.toString());
        searchResponse = searchRequestBuilder.execute().actionGet();
       log.info("response=" + searchResponse.toString());
        
        relocaAggregations = (StringTerms) searchResponse.getAggregations().asList().get(0);
        buckets = relocaAggregations.getBuckets();
        
        Map<String, Long> pointAreaMap = new HashMap<>();
        for (StringTerms.Bucket bucket : buckets) {
            String key = bucket.getKeyAsString();
            long docCount = bucket.getDocCount();
            
            String[] types = StringUtils.split(key, ",");
            for (String poorType : types) {
                if (pointAreaMap.containsKey(poorType)) {
                    pointAreaMap.put(poorType, (pointAreaMap.get(poorType) + docCount));
                } else {
                    pointAreaMap.put(poorType, docCount);
                }
            }
        }
        //转化数据字典值
        List<PointStaticsChartVo> pointSite = new ArrayList<>();
        for (Map.Entry<String, Long> entry : pointAreaMap.entrySet()) {
            String poorTypeId = entry.getKey();
            if (StringUtils.equalsIgnoreCase(DataConsts.UNKNOWN, poorTypeId)) {
                continue;
            }
            Long poorObjCount = entry.getValue();
            String poorTypeName = commonDataComponent.getSysDicValueById(poorTypeId);
            PointStaticsChartVo pointStaticsChartVo = new PointStaticsChartVo(poorTypeId, poorTypeName, poorObjCount);
            pointSite.add(pointStaticsChartVo);
        }
        
        
        //房屋类型
        searchRequestBuilder = esClientManager.getESClient().prepareSearch("pl_placementpoint_inf").setTypes("placementpoint_inf").setSize(0).setQuery
                (areacodequery);
        
        removalAgg = AggregationBuilders.terms("type").field("a_housetype.keyword")
                .size(1000);
        searchRequestBuilder.addAggregation(removalAgg);
        
       log.info("request=" + searchRequestBuilder.toString());
        searchResponse = searchRequestBuilder.execute().actionGet();
       log.info("response=" + searchResponse.toString());
        
        relocaAggregations = (StringTerms) searchResponse.getAggregations().asList().get(0);
        buckets = relocaAggregations.getBuckets();
        
        Map<String, Long> pointTypeMap = new HashMap<>();
        for (StringTerms.Bucket bucket : buckets) {
            String key = bucket.getKeyAsString();
            long docCount = bucket.getDocCount();
            
            String[] types = StringUtils.split(key, ",");
            for (String poorType : types) {
                if (pointTypeMap.containsKey(poorType)) {
                    pointTypeMap.put(poorType, (pointTypeMap.get(poorType) + docCount));
                } else {
                    pointTypeMap.put(poorType, docCount);
                }
            }
        }
        //转化数据字典值
        List<PointStaticsChartVo> pointType = new ArrayList<>();
        for (Map.Entry<String, Long> entry : pointTypeMap.entrySet()) {
            String poorTypeId = entry.getKey();
            if (StringUtils.equalsIgnoreCase(DataConsts.UNKNOWN, poorTypeId)) {
                continue;
            }
            Long poorObjCount = entry.getValue();
            String poorTypeName = commonDataComponent.getSysDicValueById(poorTypeId);
            PointStaticsChartVo pointStaticsChartVo = new PointStaticsChartVo(poorTypeId, poorTypeName, poorObjCount);
            pointType.add(pointStaticsChartVo);
        }
        
        
        return new CommonResultData<PlacementPointChartVo>(HttpStatus.OK.value(), "suc", new PlacementPointChartVo(pointArea, pointSite, pointType,
                                                                                                                   pointPQ));
    }
    
    @Override
    public PageResultData<List<PlacementPointBaseInfoVo>> searchPlacementPointBaseInfo(SearchPlacementPointVo searchPlacementPoint) throws
            YJHHException {
        if (XaUtil.isEmpty(searchPlacementPoint)) {
            return new PageResultData(HttpStatus.OK.value(), "no data");
        }
        
        String area = searchPlacementPoint.getArea();
        List<String> site = searchPlacementPoint.getSite(); //安置点选址
        List<String> type = searchPlacementPoint.getType(); //安置点类型
        List<String> peopleNum = searchPlacementPoint.getPeopleNum(); //安置人数
        List<String> position = searchPlacementPoint.getPosition(); //岗位
        int pageNum = searchPlacementPoint.getPageNum() < 1 ? 1 : searchPlacementPoint.getPageNum();
        int size = searchPlacementPoint.getSize() < 1 ? 10 : searchPlacementPoint.getSize();
        
        String areaCode = searchPlacementPoint.getAreaCode();
        
        DeptBean sysDeptInfo = commonDataComponent.getSysDeptInfo(areaCode);
        
        BoolQueryBuilder areacodequery = boolQuery().must(termQuery("a_deletestate", "0"));
        areacodequery.must(termQuery("a_ispoint", "1"));
        
        if (!XaUtil.isEmpty(area)) {
            if (sysDeptInfo.getDeptLevel() != 1) {
                if (!area.equals(sysDeptInfo.getAreaType())) {
                    return new PageResultData(HttpStatus.OK.value(), "no data");
                }
                if (area.equals(sysDeptInfo.getAreaType())) {
                    areacodequery.must(prefixQuery("a_deptno.keyword", sysDeptInfo.getDeptno()));
                }
            } else {
                areacodequery.must(termQuery("c_areatype.keyword", area));
            }
        } else {
            areacodequery.must(prefixQuery("a_deptno.keyword", sysDeptInfo.getDeptno()));
        }
        
        if (!XaUtil.isEmpty(site)) {
            for (int i = 0; i < site.size(); i++) {
                if (XaUtil.isEmpty(site.get(i))) {
                    site.remove(i);
                }
            }
            
            if (site.size() > 0) {
                areacodequery.must(termsQuery("a_seladdress", site));
            }
        }
        
        if (!XaUtil.isEmpty(type)) {
            for (int i = 0; i < type.size(); i++) {
                if (XaUtil.isEmpty(type.get(i))) {
                    type.remove(i);
                }
            }
            
            if (type.size() > 0) {
                areacodequery.must(termsQuery("a_housetype", type));
            }
        }
        
        if (!XaUtil.isEmpty(peopleNum)) {
            String minPeople = peopleNum.get(0);
            String maxPeople = peopleNum.get(1);
            
            if (!XaUtil.isEmpty(minPeople) || !XaUtil.isEmpty(maxPeople)) {
                RangeQueryBuilder rangequerybuilder = QueryBuilders.rangeQuery("b_point_placement_allrs");
                if (!XaUtil.isEmpty(minPeople) && !XaUtil.isEmpty(maxPeople)) {
                    rangequerybuilder.from(minPeople).to(maxPeople);
                }
                if (!XaUtil.isEmpty(minPeople) && XaUtil.isEmpty(maxPeople)) {
                    rangequerybuilder.from(minPeople);
                }
                if (XaUtil.isEmpty(minPeople) && !XaUtil.isEmpty(maxPeople)) {
                    rangequerybuilder.to(maxPeople);
                }
                areacodequery.must(rangequerybuilder);
            }
        }
        
        if (!XaUtil.isEmpty(position)) {
            String minCount = position.get(0);
            String maxCount = position.get(1);
            
            if (!XaUtil.isEmpty(minCount) || !XaUtil.isEmpty(maxCount)) {
                RangeQueryBuilder rangequerybuilder = QueryBuilders.rangeQuery("b_point_contruction_alljob");
                if (!XaUtil.isEmpty(minCount) && !XaUtil.isEmpty(maxCount)) {
                    rangequerybuilder.from(minCount).to(maxCount);
                }
                if (!XaUtil.isEmpty(minCount) && XaUtil.isEmpty(maxCount)) {
                    rangequerybuilder.from(minCount);
                }
                if (XaUtil.isEmpty(minCount) && !XaUtil.isEmpty(maxCount)) {
                    rangequerybuilder.to(maxCount);
                }
                areacodequery.must(rangequerybuilder);
            }
        }
        
        int pageSize = pageNum - 1;
        
        FieldSortBuilder sort = new FieldSortBuilder("a_pointid.keyword");
        SearchRequestBuilder searchRequestBuilder = esClientManager.getESClient().prepareSearch("pl_placementpoint_inf").setTypes
                ("placementpoint_inf").setFrom(pageSize * size).setSize(size).setQuery
                (areacodequery).addSort(sort);
        
       log.info("request=" + searchRequestBuilder.toString());
        SearchResponse searchResponse = searchRequestBuilder.execute().actionGet();
       log.info("response=" + searchResponse.toString());
        
        long count = searchResponse.getHits().getTotalHits();
        SearchHit[] hits = searchResponse.getHits().getHits();
        if (hits == null || hits.length <= 0) {
            new CommonResultData<>(HttpStatus.OK.value(), "suc", null);
        }
        List<PlacementPointBaseInfoVo> placementPointBaseInfoVos = new ArrayList<>();
        for (int i = 0; i < hits.length; i++) {
            Map<String, Object> searchHitSource = hits[i].getSource();
            //安置点基本信息--------------------------------------------------------------------
            PlacementPointBaseInfoVo placementPointBaseInfoVo = new PlacementPointBaseInfoVo(
                    DataTools.convertToStr(searchHitSource.get("a_allareas"), "亩"),
                    DataTools.convertToStr(searchHitSource.get("a_constructioncycle")),
                    commonDataComponent.getSysDicValueById(DataTools.convertToStr(searchHitSource.get("a_demostate"))),
                    XaUtil.dateConvertYYYYMMDD(searchHitSource.get("a_endprojecttime")),
                    DataTools.convertToStr(searchHitSource.get("a_firstyear")),
                    commonDataComponent.getSysDicValueById(DataTools.convertToStr(searchHitSource.get("a_housetype"))),
                    StringUtils.equalsIgnoreCase("1", DataTools.convertToStr(searchHitSource.get("a_isincity"))) ? "是" : "否",
                    DataTools.convertToStr(searchHitSource.get("a_pointaddress")),
                    DataTools.convertToStr(searchHitSource.get("a_pointid")),
                    commonDataComponent.getSysDicValueById(DataTools.convertToStr(searchHitSource.get("a_pointtype"))),
                    StringUtils.isBlank(DataTools.convertToStr(searchHitSource.get("a_pointx"))) ? 0.0 : Double
                            .parseDouble
                                    (DataTools.convertToStr(searchHitSource.get("a_pointx"))),
                    StringUtils.isBlank(DataTools.convertToStr(searchHitSource.get("a_pointy"))) ? 0.0 : Double
                            .parseDouble
                                    (DataTools.convertToStr(searchHitSource.get("a_pointy"))),
                    DataTools.convertToStr(searchHitSource.get("a_projname")),
                    XaUtil.dateConvert(searchHitSource.get("a_recordtime")),
                    commonDataComponent.getSysDicValueById(DataTools.convertToStr(searchHitSource.get("a_seladdress"))),
                    XaUtil.dateConvertYYYYMMDD(searchHitSource.get("a_startprojecttime")),
                    DataTools.convertToStr(searchHitSource.get("a_usercname")),
                    DataTools.convertToStr(searchHitSource.get("b_point_placement_allhs")),
                    DataTools.convertToStr(searchHitSource.get("b_point_placement_allrs"))
            );
            
            placementPointBaseInfoVos.add(placementPointBaseInfoVo);
        }
        
        return new PageResultData<>(HttpStatus.OK.value(), "suc", placementPointBaseInfoVos, count, pageNum, size);
    }
    
    @Override
    public CommonResultData<PlacementPointSimpleBaseInfoVo> getPlacementPointDetailByPointName(String pointName) throws YJHHException {
        BoolQueryBuilder boolQueryBuilder = boolQuery().must(termQuery("a_deletestate", "0"));
        boolQueryBuilder.must(termQuery("a_ispoint", "1"));
        boolQueryBuilder.must(termQuery("a_projname.keyword", pointName));
        
        SearchRequestBuilder searchRequestBuilder = esClientManager.getESClient().prepareSearch("pl_placementpoint_inf").setTypes
                ("placementpoint_inf");
        searchRequestBuilder.setQuery(boolQueryBuilder);
        
        log.info("request=" + searchRequestBuilder.toString());
        SearchResponse searchResponse = searchRequestBuilder.execute().actionGet();
        log.info("response=" + searchResponse.toString());
        SearchHit[] hits = searchResponse.getHits().getHits();
        if (hits == null || hits.length <= 0) {
            return new CommonResultData<>(HttpStatus.OK.value(), "suc", null);
        }
        SearchHit hit = hits[0];
        Map<String, Object> searchHitSource = hit.getSource();
        
        //安置点基本信息--------------------------------------------------------------------
        PlacementPointSimpleBaseInfoVo placementPointSimpleBaseInfoVo = new PlacementPointSimpleBaseInfoVo(DataTools.convertToStr(searchHitSource
                                                                                                                                          .get
                                                                                                                                                  ("a_projname")),
                                                                                                           DataTools.convertToStr(searchHitSource
                                                                                                                                          .get
                                                                                                                                                  ("a_firstyear")),
                                                                                                           DataTools.convertToStr(searchHitSource
                                                                                                                                          .get
                                                                                                                                                  ("a_city")) +
                                                                                                                   DataTools.convertToStr
                                                                                                                           (searchHitSource.get
                                                                                                                                   ("a_country")) +
                                                                                                                   DataTools.convertToStr
                                                                                                                           (searchHitSource.get
                                                                                                                                   ("a_town")),
                                                                                                           commonDataComponent.getSysDicValueById
                                                                                                                   (DataTools.convertToStr
                                                                                                                           (searchHitSource
                                                                                                                                    .get
                                                                                                                                            ("a_pointtype"))),
                                                                                                           commonDataComponent.getSysDicValueById
                                                                                                                   (DataTools.convertToStr
                                                                                                                           (searchHitSource
                                                                                                                                    .get
                                                                                                                                            ("a_housetype"))),
                                                                                                           DataTools.convertToStr(searchHitSource
                                                                                                                                          .get
                                                                                                                                                  ("b_point_placement_allhs")),
                                                                                                           DataTools.convertToStr(searchHitSource
                                                                                                                                          .get
                                                                                                                                                  ("b_point_placement_allrs")),
                                                                                                           XaUtil.dateConvertYYYYMMDD
                                                                                                                   (searchHitSource.get
                                                                                                                           ("a_startprojecttime")),
                                                                                                           XaUtil.dateConvertYYYYMMDD
                                                                                                                   (searchHitSource.get
                                                                                                                           ("a_endprojecttime")),
                                                                                                           commonDataComponent.getSysDicValueById
                                                                                                                   (DataTools.convertToStr
                                                                                                                           (searchHitSource
                                                                                                                                                   .get("a_seladdress"))),
                                                                                                           DataTools.convertToStr(searchHitSource
                                                                                                                                          .get
                                                                                                                                                  ("b_point_contruction_azdzts")),
                                                                                                           DataTools.convertToStr(searchHitSource
                                                                                                                                          .get
                                                                                                                                                  ("a_allareas")),
                                                                                                           DataTools.convertToStr(searchHitSource
                                                                                                                                          .get
                                                                                                                                                  ("b_point_contruction_allmj")));
        return new CommonResultData<>(HttpStatus.OK.value(), "suc", placementPointSimpleBaseInfoVo);
    }
    
    @Override
    public CommonResultData<List<PlacementPointBaseInfoVo>> getPlacementPointListByPointName(String pointName) throws YJHHException {
        BoolQueryBuilder boolQueryBuilder = boolQuery().must(termQuery("a_deletestate", "0"));
        boolQueryBuilder.must(termQuery("a_ispoint", "1"));
        boolQueryBuilder.must(matchQuery("a_projname", pointName));
        
        SearchRequestBuilder searchRequestBuilder = esClientManager.getESClient().prepareSearch("pl_placementpoint_inf").setTypes
                ("placementpoint_inf");
        searchRequestBuilder.setQuery(boolQueryBuilder);
        searchRequestBuilder.setFrom(0);
        searchRequestBuilder.setSize(10);
        
        log.info("request=" + searchRequestBuilder.toString());
        SearchResponse searchResponse = searchRequestBuilder.execute().actionGet();
        log.info("response=" + searchResponse.toString());
        List<PlacementPointBaseInfoVo> result = new ArrayList<>();
        SearchHit[] hits = searchResponse.getHits().getHits();
        for (SearchHit hit : hits) {
            PlacementPointBaseInfoVo vo = new PlacementPointBaseInfoVo();
            Map<String, Object> source = hit.getSource();
            vo.setPointId(DataTools.convertToStr(source.get("a_pointid")));
            vo.setPROJNAME(DataTools.convertToStr(source.get("a_projname")));
            result.add(vo);
        }
        return new CommonResultData<>(HttpStatus.OK.value(), "suc", result);
    }
    
    @Override
    public CommonResultData<List<PlacementPointSimpleBaseInfoVo>> getAllPlacementPointList() throws YJHHException {
        BoolQueryBuilder boolQueryBuilder = boolQuery().must(termQuery("a_deletestate", "0"));
        boolQueryBuilder.must(termQuery("a_ispoint", "1"));
        
        SearchRequestBuilder searchRequestBuilder = esClientManager.getESClient().prepareSearch("pl_placementpoint_inf").setTypes
                ("placementpoint_inf");
        
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        searchSourceBuilder.fetchSource(new String[]{"a_pointid", "a_projname", "a_allareas",
                "b_point_placement_allhs", "b_point_placement_allrs", "a_recordtime"}, null);
        searchSourceBuilder.query(boolQueryBuilder);
        searchSourceBuilder.sort("a_recordtime", SortOrder.DESC);
        searchSourceBuilder.size(8000);
        
        searchRequestBuilder.setSource(searchSourceBuilder);
        
        log.info("request=" + searchRequestBuilder.toString());
        SearchResponse searchResponse = searchRequestBuilder.execute().actionGet();
        log.info("response=" + searchResponse.toString());
        
        SearchHit[] hits = searchResponse.getHits().getHits();
        List<PlacementPointSimpleBaseInfoVo> list = new ArrayList<>();
        for (SearchHit hit : hits) {
            Map<String, Object> searchHitSource = hit.getSource();
            list.add(new PlacementPointSimpleBaseInfoVo(DataTools.convertToStr(searchHitSource.get("a_projname")),
                                                        DataTools.convertToStr(searchHitSource.get("b_point_placement_allhs")),
                                                        DataTools.convertToStr(searchHitSource.get("b_point_placement_allrs")),
                                                        DataTools.convertToStr(searchHitSource.get("a_allareas")),
                                                        XaUtil.dateConvertYYYYMMDD(searchHitSource.get("a_recordtime")),
                                                        DataTools.convertToStr(searchHitSource.get("a_pointid")))
            );
        }
        
        return new CommonResultData<>(HttpStatus.OK.value(), "suc", list);
    }
}
